首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >取一些以指定单词为中心的单词。

取一些以指定单词为中心的单词。
EN

Stack Overflow用户
提问于 2016-11-04 20:04:56
回答 3查看 69关注 0票数 0

有人能告诉我,我怎样才能考虑一个词周围的单词吗?如果我们有一句话:“今天天气很好,我们喜欢走路。”然后,如果窗口大小为5,我想得到以下内容:

  • 今天的天气(中心:“今天”)
  • 今天的天气是(中心:“)
  • 今天天气很好(中心:“天气”)
  • 天气很好,(中心:" is ")
  • 天气晴朗,我们(中心:“晴天”)
  • 是好的,我们爱(中间:“和”)

诸若此类。考虑到大写并不是问题:

代码语言:javascript
运行
复制
bigrams = [p for s in corpus_lemm for p in nltk.bigrams(w for w in s)] #take bigrams inside of each sentence

但是,如何考虑给定窗口大小的单词呢?

非常感谢您的帮助!

EN

回答 3

Stack Overflow用户

发布于 2016-11-04 21:33:37

对不起,我对Python没有太多的控制,但是在JS中,可以这样做。希望您可以将其实现到Python中。

代码语言:javascript
运行
复制
var str = "Today the weather is fine and we love to walk.",
    arr = str.split(/\s+/),
    win = 5,
 result = arr.map((w,i,a) => Array(win).fill()
                                       .map((e,j) => a[i + j + -1 * Math.floor(win/2)])
                                       .reduce((p,c) => p ? c ? p + " " + c
                                                              : p
                                                          : c));
 console.log(result);

根据你的评论..。在坚持同样的算法的同时,我可能会扩展我的答案如下。

代码语言:javascript
运行
复制
var arr = [1,2,3,4,5,6,7,8],
    win = 5,
 result = arr.map((_,i,a) => Array(win).fill()
                                       .map((e,j) => a[i + j + -1 * Math.floor(win/2)])
                                       .reduce((p,c) => p ? c ? [].concat(p,c)
                                                              : p
                                                          : c ? c
                                                              : undefined));
 console.log(JSON.stringify(result));

票数 0
EN

Stack Overflow用户

发布于 2016-11-04 21:55:42

我不太确定我是否理解窗口,但似乎是您想要的输出。

代码语言:javascript
运行
复制
s = "Today the weather is fine and we love to walk"
words = s.split()
win_len = 5

half_win = win_len // 2

print "\n".join(words[:half_win])

for i in range(len(words) - win_len + 1):
    window = words[i:i+win_len]
    # print " ".join(window)
    print window[len(window) // 2]

print "\n".join(words[-half_win:])

输出

代码语言:javascript
运行
复制
Today
the
weather
is
fine
and
we
love
to
walk
票数 0
EN

Stack Overflow用户

发布于 2016-11-04 22:36:59

您可以使用list.index和列表切片来检索所需的单词。

代码语言:javascript
运行
复制
def words(text, search, window):
    words = s.split()
    i = words.index(search)

    low = i - window // 2
    high = low + window
    low = max(low, 0)

    return words[low:high]
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40430931

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档