【问题标题】:Python - Finding the list of words that occurs n times in the given filePython - 查找给定文件中出现 n 次的单词列表
【发布时间】:2023-04-09 13:57:01
【问题描述】:

我想找到在给定文件中出现 n 次(例如 200 次)的单词列表。为此,我使用以下代码获取文件中的每个唯一标记,但我无法理解如何获取具有发生 n 次条件的标记。

from collections import Counter
import re

seen = list()
words = re.findall(r'[\w+]+', open('deneme.txt').read())
seen = Counter(words).most_common()

输出是:

[('Erke', 4), ('aç+Noun', 4), ('Antalya', 3), ('123', 3), ('ol+Verb', 3), ('Varol', 2), ('Koleji', 1), ('asdfsdf', 1), ('birak+Verb', 1)]

例如,我想获得出现 3 次的令牌。我怎样才能做到这一点。我无法达到列表中的出现次数。

【问题讨论】:

  • 一个更简单的方法是创建一个包含所有单词的字典,每个单词的计数值为,然后查看字典中出现 n 次的所有单词
  • [ (x,y) for (x,y) in your_array_element if y == 3 ]
  • @SPYBUG96 这并不比列表理解更容易。无论哪种方式,您最终都会循环通过dict/list

标签: python python-3.x list counter


【解决方案1】:

你可以使用list comprehension:

from collections import Counter
import re

seen = list()
words = re.findall(r'[\w+]+', open('deneme.txt').read())
seen = Counter(words).most_common()

print([w for w, c in seen if c == 3])

输出

 ['123', 'Antalya', 'ol+Verb']

【讨论】:

  • 如果列表中的元组元素过多,[e[0] for e in seen if e[1] == 3] 会很有用。
  • @RockyLi 在什么情况下会发生这种情况? Counter.most_common 总是产生宽度为 2 的元组。
猜你喜欢
  • 2021-12-15
  • 1970-01-01
  • 2013-02-11
  • 1970-01-01
  • 1970-01-01
  • 2012-12-30
  • 2014-11-08
  • 2012-12-14
  • 2018-01-14
相关资源
最近更新 更多