Hyp*_*nja 20 python list-comprehension list nltk collocation
我有一个句子列表:
text = ['cant railway station','citadel hotel',' police stn'].
Run Code Online (Sandbox Code Playgroud)
我需要形成双字节对并将它们存储在变量中.问题是,当我这样做时,我会得到一对句子而不是单词.这是我做的:
text2 = [[word for word in line.split()] for line in text]
bigrams = nltk.bigrams(text2)
print(bigrams)
Run Code Online (Sandbox Code Playgroud)
产量
[(['cant', 'railway', 'station'], ['citadel', 'hotel']), (['citadel', 'hotel'], ['police', 'stn'])
Run Code Online (Sandbox Code Playgroud)
不能火车站和城堡酒店组成一个二元组.我想要的是
[([cant],[railway]),([railway],[station]),([citadel,hotel]), and so on...
Run Code Online (Sandbox Code Playgroud)
第一句的最后一个单词不应与第二句的第一个单词合并.我该怎么做才能让它发挥作用?
but*_*tch 37
>>> text = ["this is a sentence", "so is this one"]
>>> bigrams = [b for l in text for b in zip(l.split(" ")[:-1], l.split(" ")[1:])]
>>> print(bigrams)
[('this', 'is'), ('is', 'a'), ('a', 'sentence'), ('so', 'is'), ('is', 'this'), ('this',
'one')]
Run Code Online (Sandbox Code Playgroud)
小智 7
from nltk import word_tokenize
from nltk.util import ngrams
text = ['cant railway station', 'citadel hotel', 'police stn']
for line in text:
token = nltk.word_tokenize(line)
bigram = list(ngrams(token, 2))
# the '2' represents bigram...you can change it to get ngrams with different size
Run Code Online (Sandbox Code Playgroud)
不是将文本转换为字符串列表,而是将每个句子分别作为字符串单独开头.我还删除了标点符号和停用词,如果与您无关,请删除这些部分:
import nltk
from nltk.corpus import stopwords
from nltk.stem import PorterStemmer
from nltk.tokenize import WordPunctTokenizer
from nltk.collocations import BigramCollocationFinder
from nltk.metrics import BigramAssocMeasures
def get_bigrams(myString):
tokenizer = WordPunctTokenizer()
tokens = tokenizer.tokenize(myString)
stemmer = PorterStemmer()
bigram_finder = BigramCollocationFinder.from_words(tokens)
bigrams = bigram_finder.nbest(BigramAssocMeasures.chi_sq, 500)
for bigram_tuple in bigrams:
x = "%s %s" % bigram_tuple
tokens.append(x)
result = [' '.join([stemmer.stem(w).lower() for w in x.split()]) for x in tokens if x.lower() not in stopwords.words('english') and len(x) > 8]
return result
Run Code Online (Sandbox Code Playgroud)
要使用它,请这样做:
for line in sentence:
features = get_bigrams(line)
# train set here
Run Code Online (Sandbox Code Playgroud)
请注意,这会更进一步,实际上统计得分为bigrams(这将在训练模型时派上用场).
如果没有nltk:
ans = []
text = ['cant railway station','citadel hotel',' police stn']
for line in text:
arr = line.split()
for i in range(len(arr)-1):
ans.append([[arr[i]], [arr[i+1]]])
print(ans) #prints: [[['cant'], ['railway']], [['railway'], ['station']], [['citadel'], ['hotel']], [['police'], ['stn']]]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
48774 次 |
| 最近记录: |