![](/img/trans.png)
[英]How to count the number of times a word appears for specific fields using python?
[英]How count the number of times a letter appears in word using python
有沒有更好的方法來寫出這個 python 代碼 - 計算一個字母出現在一個單詞中的次數。例如,“特質”在單詞中有兩個字母“y”。我如何計算和輸出 a 的次數字母出現在一個詞中。 只是試圖用 for 循環和 while 語句保持簡單。仍然是一個 python 新手。
示例代碼:
def display():
letter = str(input('enter a letter: '))
word = str(input('enter a word: '))
print(countNum(word,letter))
def countNum(letter, word):
count = 0
index = 0
for letter in word:
if str(word[index]) == letter :
print(count)
count = count + 1
x = "testert"
print(x.count("e"))
print(x.count("t"))
您可以使用它輕松完成。
輸出:
2
3
def print_count(pr):
for item in pr:
print(item, pr.count(item))
def unique(sequence):
seen = set()
return [x for x in sequence if not (x in seen or seen.add(x))]
def print_count(pr):
for item in unique(pr):
print(item, pr.count(item))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.