【问题标题】:Remove fullstop, commas, quotation from list in Python从 Python 列表中删除句号、逗号、引号
【发布时间】:2014-02-19 10:28:47
【问题描述】:

我有一个用于从文本文件中计算词频的 python 代码。该程序的问题在于它考虑了句号,因此改变了计数。为了计算单词,我使用了一个排序的单词列表。我试图删除句号使用

 words = open(f, 'r').read().lower().split()  
 uniqueword = sorted(set(words))
 uniqueword = uniqueword.replace(".","") 

但我得到错误

AttributeError: 'list' object has no attribute 'replace'

任何帮助将不胜感激:)

【问题讨论】:

  • 目前尚不清楚您遇到了什么问题。您是否发现您的单词带有尾随标点符号?还是您发现“单词”列表中有标点符号?
  • 我得到的输出:Words Count blondes 4 blondes. 2 都是同一个词,唯一的区别是一个出现在句子的中间,而另一个出现在句子的末尾。

标签: python-2.7 word-frequency


【解决方案1】:

您可以在创建set 之前使用列表推导来处理单词:

words = [word.replace(".", "") for word in words]

您也可以在 (uniquewords = [word.replace...]) 之后删除它们,但随后您将重新引入重复项。

请注意,如果您想计算这些单词,Counter 可能更有用:

from collections import Counter

counts = Counter(words)

【讨论】:

    【解决方案2】:

    你可能会更好

    words = re.findall(r'\w+', open(f, 'r').read().lower())
    

    它将抓取由一个或多个“单词字符”组成的所有字符串,并忽略标点符号和空格。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-04-29
      • 1970-01-01
      • 1970-01-01
      • 2021-05-31
      • 2020-04-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多