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

2024-10-02 06:30:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我是python新手,但编程经验丰富。在学习python时,我试图创建一个简单的函数,从文本文件中读入单词(文本文件中的每一行都是一个新词),然后检查每个单词是否有字母“e”。然后,程序应该计算没有字母“e”的单词的数量,并使用该数量计算文本文件中没有字母“e”的单词的百分比

我遇到了一个问题,我非常确定我的代码是正确的,但在测试了输出之后,它是错误的。请帮忙

代码如下:

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)

Tags: 代码infalsefor数量ifcount字母
1条回答
网友
1楼 · 发布于 2024-10-02 06:30:01

以下是进行一些可能有帮助的更改后的代码:

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)

希望这会有所帮助

相关问题 更多 >

    热门问题