【问题标题】:Python 3 counter that is ignoring strings with less than x charactersPython 3 计数器忽略少于 x 个字符的字符串
【发布时间】:2020-02-13 11:25:17
【问题描述】:

我有一个计算文本文件字数的程序。现在我想将计数器限制为超过 x 个字符的字符串

from collections import Counter
input = 'C:/Users/micha/Dropbox/IPCC_Boox/FOD_v1_ch15.txt'

Counter = {}
words = {}
with open(input,'r', encoding='utf-8-sig') as fh:
  for line in fh:
    word_list = line.replace(',','').replace('\'','').replace('.','').lower().split()
    for word in word_list:
      if word not in Counter:
        Counter[word] = 1
      else:
        Counter[word] = Counter[word] + 1
N = 20
top_words = Counter(Counter).most_common(N)
for word, frequency in top_words:
    print("%s %d" % (word, frequency))

我尝试了re 代码,但它不起作用。

    re.sub(r'\b\w{1,3}\b')

我不知道如何实现它...

最后,我想要一个忽略所有短词的输出,例如 and, you, be 等。

【问题讨论】:

  • 为什么要构建手动计数器?

标签: python string counter analysis word


【解决方案1】:

一些注释。

1) 您导入了 Counter 但没有正确使用它(您执行了 Counter = {} 从而覆盖了导入)。

from collections import Counter

2) 与其使用set 进行多个replaces 使用列表理解,它更快并且只进行一次(两个与连接)迭代而不是多次:

sentence = ''.join([char for char in line if char not in {'.', ',', "'"}])
word_list = sentence.split()

3) 使用计数器和列表计算长度:

c = Counter(word for word in word_list if len(word) > 3)

就是这样。

【讨论】:

    【解决方案2】:

    计数器已经做了你想要的。您可以用可迭代的方式“喂”它,这将起作用。 https://docs.python.org/2/library/collections.html#counter-objects 你也可以使用过滤功能https://docs.python.org/3.7/library/functions.html#filter 可能看起来很像:

    counted = Counter(filter(lambda x: len(x) >= 5, words))

    【讨论】:

      【解决方案3】:

      你可以更简单地做到这一点:

        for word in word_list:
            if len(word) < 5:   # check the length of each word is less than 5 for example
                continue        # this skips the counter portion and jumps to next word in word_list
            elif word not in Counter:
                Counter[word] = 1
            else:
                Counter[word] = Counter[word] + 1
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-04-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-05-26
        • 1970-01-01
        • 2017-06-12
        相关资源
        最近更新 更多