【问题标题】:Loop within a loop not re-looping with reading a file Python3循环内循环不通过读取文件Python3重新循环
【发布时间】:2013-10-29 23:03:12
【问题描述】:

尝试编写一段代码,在文本文件中查找所有特定类型的字符 对于元音,它会找到所有 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

【问题讨论】:

  • 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 (字符)返回找到
  • 当您不使用line 时,为什么finder_character 会循环覆盖line in in_file
  • 这应该回答我的问题吗?因为它没有。
  • 你打算brain_rat[i+1,i+2]做什么?此语法对于 lists 是不合法的。
  • @SandiWilliams 我认为您将尝试做的事情复杂化了。在下面查看我修改后的答案,该答案解释了如何逐步浏览文件。

标签: python file loops


【解决方案1】:

如果你想使用你的原始代码,你必须将文件名传递给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())

test.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

【讨论】:

    【解决方案2】:

    这似乎是您在finder_character 中尝试做的事情。我不知道你为什么需要finder

    在 python 中,您可以循环遍历可迭代对象(如字符串),因此您无需执行 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() 更好,因为您不必担心错误处理和关闭。我添加了一些 cmets 来帮助解释您要执行的操作。

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-04-10
      • 2015-01-04
      • 2015-05-21
      • 1970-01-01
      • 2017-07-02
      • 1970-01-01
      • 1970-01-01
      • 2016-04-24
      相关资源
      最近更新 更多