【发布时间】:2021-03-01 11:46:11
【问题描述】:
我正在尝试从单词列表中的 string.punctuation 列表中删除标点符号。问题是我不知道在哪里删除标点符号,因为我正在处理字典中的字典。我的代码如下
from collections import Counter
import re
comments = []
ar_lst = []
for review in reviews:
ar_dict = {}
ar_dict["Comments"] = review["Content"]
ar_dict["Author"] = review["Author"]
ar_lst.append(ar_dict)
for review in ar_lst:
# TODO: (1) Get the number of words in the current review variable.
punc= string.punctuation
comments = review['Comments'].lower()
author = review['Author']
unique_words_count = set()
all_words = comments.split(" ")
for word in all_words:
unique_words_count.add(word)
# (2) Print the author's name and the number of (unique) words in his/her review
print(f'{author} used {len(unique_words_count)} unique words.')
我得到的输出如下
但我需要输出看起来像这样
# of words 关闭的原因是我不知道在哪里插入 re.sub() 表达式。我试着把它放到第二个'for-loop'中
comments = re.sub(punc, '', review['Comments']).lower()
但这不起作用。任何帮助将不胜感激!
另外,这是字典的样子
【问题讨论】:
-
请将数据发布为文本而不是图像。您可以在拆分 cmets 之前去掉标点符号,也可以在循环
for word in all_words:中处理每个word。当您使用一套时,您不必担心重复。 -
当您可以将非单词与
\W之类的东西匹配时,使用string.punctuation有点不寻常