【问题标题】:Python - Strip Punctuation from list of words using re.sub and string.punctuationPython - 使用 re.sub 和 string.punctuation 从单词列表中去除标点符号
【发布时间】: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 有点不寻常

标签: python regex


【解决方案1】:

您可以在拆分成单词之前从comments 中删除标点符号(首选),或者您可以在循环for word in all_words: 中从word 中删除它。 string.punctuation 是一个字符串 !"#$%&'... 但您可能需要字符集:

punc = '[%s]' % string.punctuation.replace(']', '\]')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-01-01
    • 1970-01-01
    • 2013-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-26
    相关资源
    最近更新 更多