我用 Python 创建了一些代码来查找字符串中出现频率最高的单词。我对 Python 还很陌生,请求你的帮助,看看我是否可以更好、更有效地编写这个代码。
(代码返回字符串中出现频率最高的单词的一个整数。)
另外我想确保该字符串仅包含 [a-z][A-Z] ,我尝试过但不知道如何进行该检查。
from collections import Counter
class WordCounter:
def __init__(self, word, frequency):
self.word = word
self.frequency = frequency
# find_top_frequency should return the highest frequency in the text
def find_top_frequency(text: str) -> int:
incoming_string = text.split()
incoming_string= [x.lower() for x in incoming_string]
Words_in_dict_count = {}
for i in incoming_string:
if i not in Words_in_dict_count.keys():
Words_in_dict_count[i] = 0
Words_in_dict_count[i] = Words_in_dict_count[i] + 1
return (max(Words_in_dict_count.values()))
print("\n字符串中相同单词的最高频率是:" +str(WordCounter.find_top_Frequency("我很想让这段代码变得更好,但希望你能帮助我。谢谢你帮助我。希望你能帮助我."))+"\n")
Use str.isalpha()
过滤仅包含字母的单词,并使用Counter.most_common
获取最常用的单词。
>>> from collections import Counter
>>> def find_top_frequency(text: str) -> int:
... return Counter(
... word for word in text.split() if word.isalpha()
... ).most_common(1).pop()[1]
...
>>> find_top_frequency("foo bar foo foo bar 1 1 1 1 1 1")
3
注意most_common(1).pop()
is a Tuple[str, int]
单词和计数(在这种情况下是('foo', 3)
,所以如果你想要这两个而不仅仅是计数,你所要做的就是删除[1]
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)