关于用Python对一段英文所出现的单词计数的问题
正常输入单词查询是没有问题的,问题是当我输入单一字符串便会出现问题,比如我输入“a”,它便出现 a 出现的次数为15次。实际上应为1次。
学生作业,希望大家伙帮帮忙,谢谢啦
Mystr = "Python is a high-level , general-purpose programming language . Its design philosophy emphasizes code " \
"readability with the use of significant indentation . Python is dynamically typed and garbage-collected ."
print(Mystr.replace(",", "").replace(".", "").split(' '))
# print(Mystr.split(' '))
while True:
word = input("请输入要查询的单词:")
if word == "quit":
break
count = Mystr.count(word)
print(f"单词 {word} 在这段英文中出现了 {count} 次。") Python count函数是Python的字符串函数。用于统计字符串中某字符出现的次数。
也许你应该先将句子分割成列表,再统计单词出现次数 Mystr = "Python is a high-level , general-purpose programming language . Its design philosophy emphasizes code " \
"readability with the use of significant indentation . Python is dynamically typed and garbage-collected ."
这个字符串里,‘a’是出现15次啊 kof21411 发表于 2023-4-4 16:35
Mystr = "Python is a high-level , general-purpose programming language . Its design philosophy empha ...
是的,所以我不应该用count对吗?我的目标是输入单词可以查询到它出现的次数,比如a。它在这段文本里应只出现一次。出现15次是她把后面单词里面包含的a给计数了。 Arcticlyc 发表于 2023-4-4 16:31
Python count函数是Python的字符串函数。用于统计字符串中某字符出现的次数。
也许你应该先将句子分割成 ...
用了split进行了分割 Shimmer666 发表于 2023-4-4 16:41
是的,所以我不应该用count对吗?我的目标是输入单词可以查询到它出现的次数,比如a。它在这段文本里应只 ...
那你就要像二楼说的将句子分割成列表,再统计单词出现次数
或用第三方的jieba库 kof21411 发表于 2023-4-4 16:35
Mystr = "Python is a high-level , general-purpose programming language . Its design philosophy empha ...
好的谢谢 import re
def count_word(text, word):
words = re.findall(r'\b%s\b' % word, text, flags=re.IGNORECASE)
return len(words)
text = "Python is a high-level , general-purpose programming language . Its design philosophy emphasizes code readability with the use of significant indentation . Python is dynamically typed and garbage-collected ."
word = "a"
result = count_word(text, word)
print("单词'{}'出现的次数为:{}".format(word, result))
这段代码使用正则表达式\b来确保单词是独立的,并且通过设置re.IGNORECASE标志来忽略大小写 使用正则表达式,查询返回数据长度 单词的首尾加上空格,就解决问题了
页:
[1]
2