簡體   English   中英

如何在 python 中檢查字符串是否包含特定字符

[英]How to check if a string contains a specific character or not in python

我是 python 的新手,但在編程方面經驗豐富。 在學習 python 時,我試圖創建一個簡單的 function,它可以從文本文件中讀取單詞(文本文件中的每一行都是一個新單詞),然后檢查每個單詞是否包含字母“e”。 然后程序應該計算沒有字母“e”的單詞的數量,並使用該數量來計算文本文件中沒有“e”的單詞的百分比。

我遇到了一個問題,我非常確定我的代碼是正確的,但是在測試 output 之后它是錯誤的。 請幫忙!

這是代碼:

def has_n_e(w):
    hasE = False
    for c in w:
        if c == 'e':
            hasE = True
    return hasE

f = open("crossword.txt","r")
count = 0

for x in f:
    word = f.readline()
    res = has_n_e(word)
    if res == False:
        count = count + 1

iAns = (count/113809)*100 //113809 is the amount of words in the text file
print (count)
rAns = round(iAns,2)
sAns = str(rAns)
fAns = sAns + "%"
print(fAns)

這是進行一些可能有幫助的更改后的代碼:

def has_n_e(w):
    hasE = False
    for c in w:
        if c == 'e':
            hasE = True
    return hasE

f = open("crossword.txt","r").readlines()
count = 0

for x in f:
    word = x[:-1]
    res = has_n_e(word)# you can use ('e' in word) instead of the function
    if res == False:
        count = count + 1

iAns = (count/len(f))*100 //len(f) #is the amount of words in the text file
print (count)
rAns = round(iAns,2)
sAns = str(rAns)
fAns = sAns + "%"
print(fAns)

希望這會有所幫助

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM