循环中的循环不重新循环读取文件Python3

2024-05-19 21:38:30 发布

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

尝试编写一个代码,在文本文件中查找所有特定类型的字符 对于元音,它会找到所有a的数字,但不会通过文本重新循环来读取e。帮助?你知道吗

def finder_character(file_name,character):

    in_file = open(file_name, "r")

    if character=='vowel':
        brain_rat='aeiou'
    elif character=='consonant':
        brain_rat='bcdfghjklmnpqrstvwxyz'
    elif character=='space':
        brain_rat=''
    else:
        brain_rat='!@#$%^&*()_+=-123456789{}|":?><,./;[]\''       

    found=0 
    for line in in_file:
        for i in range (len(brain_rat)):
            found += finder(file_name,brain_rat[i+1,i+2])


    in_file.close()
    return found

def finder(file_name,character):
    in_file = open(file_name, "r")
    line_number = 1
    found=0
    for line in in_file:
        line=line.lower()
        found +=line.count(character)
    return found

Tags: 代码nameinforreturnfinderdefline
2条回答

如果您想使用您的原始代码,您必须将文件名传递给finder()函数,并在那里打开您要测试的每个字符的文件。你知道吗

原因是文件对象(in_file)是一个生成器,而不是一个列表。生成器的工作方式是,每次调用它们的next()方法时,它都返回下一项。当你说

for line in in_file:

for ... in语句调用in_file.next(),只要next()方法“返回”(它实际上使用了关键字yield,但现在不要考虑这个)一个值。当生成器不再返回任何值时,我们称生成器已耗尽。你不能重复使用一个耗尽的发电机。如果你想重新开始,你必须做一个新的发电机。你知道吗

我允许自己重写你的代码。这会给你想要的结果。如果有什么不清楚的地方,请询问!你知道吗

def finder_character(file_name,character):

    with open(file_name, "r") as ifile:
        if character=='vowel':
            brain_rat='aeiou'
        elif character=='consonant':
            brain_rat='bcdfghjklmnpqrstvwxyz'
        elif character=='space':
            brain_rat=' '
        else:
            brain_rat='!@#$%^&*()_+=-123456789{}|":?><,./;[]\'' 

    return sum(1 if c.lower() in brain_rat else 0 for c in ifile.read())

测试.txt:

eeehhh
iii!#
kk ="k
oo o

输出:

>>>print(finder_character('test.txt', 'vowel'))
9
>>>print(finder_character('test.txt', 'consonant'))
6
>>>print(finder_character('test.txt', 'space'))
2
>>>print(finder_character('test.txt', ''))
4

如果您在理解return行时遇到问题,则应该向后阅读,如下所示:

Sum this generator:
    Make a generator with values as v in:
        for row in ifile.read():
            if c.lower() in brain_rat:
                v = 1
            else:
                v = 0

如果您想了解有关生成器的更多信息,我推荐有关它的Python Wiki page。你知道吗

这似乎就是您在finder_character中要做的。我不知道你为什么需要finder。你知道吗

在python中,您可以在iterables上循环(比如字符串),因此不需要执行range(len(string))。你知道吗

for line in in_file:
    for i in brain_rat:
        if i in line: found += 1

您的代码中似乎还有一些其他的奇怪之处:

  • 打开(并遍历)文件两次,但只关闭一次。你知道吗
  • line_number从不使用
  • 你得到了文件中每一行的字符总数,所以总数会大大膨胀。你知道吗

这可能是一个更安全的版本,with open...通常比open()... file.close()好,因为您不需要太担心错误处理和关闭。我添加了一些注释来帮助解释您要做的事情。你知道吗

def finder_character(file_name,character):
    found=0    # Initialise the counter
    with open(file_name, "r") as in_file:
        # Open the file
        in_file = file_name.split('\n')

        opts = { 'vowel':'aeiou',
                 'consonant':'bcdfghjklmnpqrstvwxyz',
                 'space':'' }
        default= '!@#$%^&*()_+=-123456789{}|":?><,./;[]\''

        for line in in_file:
            # Iterate through each line in the file
            for c in opts.get(character,default):
                With each line, also iterate through the set of chars to check.
                if c in line.lower():
                    # If the current character is in the line
                    found += 1  # iterate the counter.
    return found    # return the counter

相关问题 更多 >