计算Python句子中字母/单词出现次数的代码(abs初学者)
最后的问题
userinput = input('please enter your sentence here: ')
wannacount = input('which character/word you want to count? ')
# lower casing user input as small & capital letters are not the same in python
lower_in = userinput.lower()
lower_wc = wannacount.lower()
count = 0
for word in lower_in:
if word == lower_wc:
count = count +1
# note: words won't be counted with this code, only letters
print(wannacount, 'appears', count, 'times in your sentence')
当仅指定一个字符时,这会给出正确的答案。但是当我输入一个单词/>=2个字符时,答案是0。
问题::
Q1。如何制作所需的计算单词和/或字符的程序?
我尝试用“lower_wc”替换“word”,并且计数给出了一些看似随机的数字。例如,“hello world”中的 11 代表字符“o”。
Q2。 11背后的逻辑是什么?
questions at the end
userinput = input('please enter your sentence here: ')
wannacount = input('which character/word you want to count? ')
# lower casing user input as small & capital letters are not the same in python
lower_in = userinput.lower()
lower_wc = wannacount.lower()
count = 0
for word in lower_in:
if word == lower_wc:
count = count +1
# note: words won't be counted with this code, only letters
print(wannacount, 'appears', count, 'times in your sentence')
This gives correct answer when only a character is specified. But when I put a word/>=2 characters, the answer is 0.
Questions::
Q1. How to make the desired program which counts word and/or character?
I tried to replace "word" with "lower_wc" and the count gives some seemingly random number. e.g. 11 in "hello world" for char "o".
Q2. What is the logic behind the 11?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
问题1的答案:
以下代码将帮助您计算一个字符串在另一个字符串中出现的次数。在count函数中,参数text是指要搜索的字符串,参数to_be_searched是指要搜索的字符串,如果设置为 True,布尔参数 case_sensitive 会进行区分大小写的匹配;如果设置为 True,布尔参数 overlapped 会搜索重叠匹配。
Answer to Q1:
The following code will help you to count the number of occurrences of a string in another string. In the count function, parameter text refers to the string in which you want to search, parameter to_be_searched refers to the string you want to search, boolean parameter case_sensitive does case-sensitive matching if set to True, and boolean parameter overlapped searches for overlapping matches if set to True.