【问题标题】:How can I remove punctuation from a dictionary in python [duplicate]如何从python中的字典中删除标点符号[重复]
【发布时间】:2016-11-04 14:23:40
【问题描述】:
wordcount = {}
    for vocab in file.read().split():
        if vocab not in wordcount:
            wordcount[vocab] = 1
        else:
            wordcount[vocab] = wordcount[vocab] + 1
    for (word,number) in wordcount.items():
        print (word, number)
print (word_count(0))

【问题讨论】:

  • 有什么问题?
  • 打印时如何从字典中删除标点符号?当我打印时,它会在单词末尾返回很多标点符号
  • 也许您应该在将单词放入字典之前从文本中删除标点符号。
  • 正如 polku 所说,在将单词添加到字典之前,您应该是 stripping 的标点符号。还可以考虑使用Counter 而不是普通的字典。

标签: python python-3.x dictionary


【解决方案1】:

正如 PM 2Ring 所说,Counter 对象在这里很有用,或者只是来自collections 库的defaultdict。我们可以使用正则表达式包re 来获得更强大的re.split() 或简单的re.findall()

from re import findall, IGNORECASE
from operator import itemgetter
from collections import defaultdict

wordcount = defaultdict(int)

file = open("license.txt")

for vocab in findall(r"[A-Z]+", file.read(), flags=IGNORECASE):
    wordcount[vocab.lower()] += 1

for word, number in sorted(wordcount.items(), key=itemgetter(1), reverse=True):
    print(word, number)

输出

> python3 test.py
the 77
or 54
of 48
to 47
software 44
and 36
any 36
for 23
license 22
you 20
this 19
agreement 18
be 17
by 16
in 16
other 14
may 13
use 11
not 10
that 10
...

总会有取舍:您可能需要微调模式以允许使用连字符或撇号,具体取决于您的应用程序。

如果输入文件相对较小,则读取整个文件并进行处理就可以了。如果没有,请使用readline() 在循环中逐行读取,然后依次处理每一行。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-22
    • 1970-01-01
    相关资源
    最近更新 更多