我解析来自新闻网站的信息。每个新闻都是存储在translated_news变量中的字典。每一条新闻都有自己的标题,网址和国家。然后,我试着重复每个新闻标题,删除停止词和标点符号。我写了这段代码:
for new in translated_news:
tk = tokenize(new['title'])
# delete punctuation signs & stop-words
for t in tk:
if (t in punkts) or (t+'\n' in stops):
tk.remove(t)
tokens.append(tk)Tokenize是一个返回令牌列表的函数。下面是输出的一个示例:
['medium', ':', 'russian', 'athlete', 'will', 'be', 'admit', 'to', 'the', '2018', 'olympics', 'in', 'neutral', 'status']这里有相同的输出,但是删除了停止词和标点符号:
['medium', 'russian', 'athlete', 'be', 'admit', 'the', 'olympics', 'neutral', 'status']问题是:即使' The‘和'be’都包含在我的停止词列表中,但它们并没有从新闻标题中删除。然而,在其他标题上,它有时是正确的:
['wada', 'acknowledge', 'the', 'reliable', 'information', 'provide', 'to', 'rodchenkov'] ['wada', 'acknowledge', 'reliable', 'information', 'provide', 'rodchenkov']
这里“the”从标题中删除了。我不明白代码有什么问题,为什么有时输出是完美的,有时不是。
发布于 2017-12-09 16:24:14
您必须在tokenize(new['title'])上迭代并使用德摩根定律来简化if语句:
import string
stops = ['will', 'be', 'to', 'the', 'in']
tk = ['medium', ':', 'russian', 'athlete', 'will', 'be', 'admit', 'to', 'the',
'2018', 'olympics', 'in', 'neutral', 'status']
# delete punctuation signs & stop-words
tk = []
for t in tokenize(new['title']):
# if not ((t in string.punctuation) or (t in stops)):
if (t not in string.punctuation) and (t not in stops): # De Morgan's laws
tk.append(t)
print(tk)将印刷:
['medium', 'russian', 'athlete', 'admit', '2018', 'olympics', 'neutral', 'status']你可以去掉停止词中的新行:
stops = ['will\n', 'be\n', 'to\n', 'the\n', 'in\n']
stops = [item.strip() for item in stops]
print(stops)将印刷:
['will', 'be', 'to', 'the', 'in']incanus86建议的解决方案确实有效:
tk = [x for x in tokenize(new['title']) if x not in stops and x not in string.punctuation]但是如果你知道清单理解,你就不会问了。
我不明白代码有什么问题,为什么有时输出是完美的,有时不是。
在迭代tk项时,您确实错过了'be'和'the',因为您正在删除代码中所示的tk项:
import string
stops = ['will', 'be', 'to', 'the', 'in']
tk = [
'medium', # 0
':', # 1
'russian', # 2
'athlete', # 3
'will', # 4
'be', # 5
'admit', # 6
'to', # 7
'the', # 8
'2018', # 9
'olympics', # 10
'in', # 11
'neutral', # 12
'status' # 13
]
# delete punctuation signs & stop-words
for t in tk:
print(len(tk), t, tk.index(t))
if (t in string.punctuation) or (t in stops):
tk.remove(t)
print(tk)将印刷:
(14, 'medium', 0)
(14, ':', 1)
(13, 'athlete', 2)
(13, 'will', 3)
(12, 'admit', 4)
(12, 'to', 5)
(11, '2018', 6)
(11, 'olympics', 7)
(11, 'in', 8)
(10, 'status', 9)
['medium', 'russian', 'athlete', 'be', 'admit', 'the', '2018', 'olympics', 'neutral', 'status']你确实想念“俄语”,是“,”“ and ”中性的“”。
“运动员”的索引是2,而“意志”的索引是3,因为你去掉了“从tk中删除”。
“承认”的索引为4,如果"to“为5,则索引为5,因为您从tk中删除了"will”。
“2018年”指数为6,“奥林匹克”指数为7,“中”指数为8,“状态”指数为9。
您不能在迭代列表时更改列表!
发布于 2017-12-03 21:56:20
试着去掉换行符。
像这样的东西
tk = [x for x in tokenize(new['title']) if x not in stops and x not in string.punctuation]https://stackoverflow.com/questions/47623108
复制相似问题