Python 如何使用NLTK从一个句子中获取成对的单词?

Python 如何使用NLTK从一个句子中获取成对的单词?,python,nlp,nltk,Python,Nlp,Nltk,我想说一句话: sentence = "How many people are here"? 并返回短语列表: pairs = ["How many", "many people", "people are", "are here"] 我试过了 tokens = nltk.word_tokenize(sentence) pairs = nltk.bigrams(tokens) 而是得到了 我是nltk的新手,很抱歉这太离谱了:)谢谢你的帮助 如您所述,nktk.bigrams(

我想说一句话:

sentence = "How many people are here"?
并返回短语列表:

pairs = ["How many", "many people", "people are", "are here"]
我试过了

   tokens = nltk.word_tokenize(sentence)
   pairs = nltk.bigrams(tokens)
而是得到了


我是nltk的新手,很抱歉这太离谱了:)谢谢你的帮助

如您所述,
nktk.bigrams()
函数返回一个生成器对象。 为了得到值,需要遍历生成器。这可以通过
list()
或在生成器上循环来完成

下面,我在列表理解中循环/迭代生成器对象(nktk.bigrams())的结果,同时使用
“”.join()
根据需要将生成器丢弃的一对(列表)单词组合成单个字符串

tokens = nltk.word_tokenize(sentence)
pairs = [ " ".join(pair) for pair in nltk.bigrams(tokens)]
[‘多少’,…]


正如您所提到的,
nktk.bigrams()
函数返回一个生成器对象。 为了得到值,需要遍历生成器。这可以通过
list()
或在生成器上循环来完成

下面,我在列表理解中循环/迭代生成器对象(nktk.bigrams())的结果,同时使用
“”.join()
根据需要将生成器丢弃的一对(列表)单词组合成单个字符串

tokens = nltk.word_tokenize(sentence)
pairs = [ " ".join(pair) for pair in nltk.bigrams(tokens)]
[‘多少’,…]


这将解决您的问题:

import re
f = open('D:\Jupyter notebook\SNPQ.txt','r')
text = f.read()
text = re.sub('^\n|\n$','',(text))
for no,line in enumerate(text.splitlines()):
    print('"'+'","'.join([i.replace('"','\\"').strip() for i in re.split('(?<=^[0-9]{2})([0-9]{13}| {13})|  +',text.splitlines()[no].strip()) if i != None])+'"')
重新导入
f=打开('D:\Jupyter notebook\SNPQ.txt','r')
text=f.read()
text=re.sub(“^\n |\n$”,“,”(text))
对于“否”,枚举中的行(text.splitlines()):

打印(“+”、“.join([i.replace(““”、“\\”)).strip(),用于重新拆分(“(?这应该可以解决您的问题:

import re
f = open('D:\Jupyter notebook\SNPQ.txt','r')
text = f.read()
text = re.sub('^\n|\n$','',(text))
for no,line in enumerate(text.splitlines()):
    print('"'+'","'.join([i.replace('"','\\"').strip() for i in re.split('(?<=^[0-9]{2})([0-9]{13}| {13})|  +',text.splitlines()[no].strip()) if i != None])+'"')
重新导入
f=打开('D:\Jupyter notebook\SNPQ.txt','r')
text=f.read()
text=re.sub(“^\n |\n$”,“,”(text))
对于“否”,枚举中的行(text.splitlines()):

打印(“+”、“\\”).join([i.replace(““+”、“\\”).strip()用于重新拆分(“(?您是否尝试
list(pairs)
或调用
next(pairs)
对生成的生成器对象进行迭代?啊,太好了。我如何将其转换为我想要的形式,即从[('How','many')]-->[“How”]尝试
list(pairs)]
或调用
next(pairs)
在生成的生成器对象上迭代生成器?太好了。我如何将其转换为我想要的形式,即从[('How','many')]-->[“How many”]你想用你的第一条评论来填写,这样我就可以接受吗?谢谢你的帮助!你想用你的第一条评论来填写,这样我就可以接受吗?谢谢你的帮助!