简体   繁体   English

循环内循环而不是通过读取文件Python3重新循环

[英]Loop within a loop not re-looping with reading a file Python3

Trying to write a code that will find all of a certain type of character in a text file For vowels it'll find all of the number of a's but won't reloop through text to read e's. 试图编写一个能够在文本文件中找到所有特定类型字符的代码对于元音,它会找到所有的数字,但不会通过文本重新循环来读取e。 help? 救命?

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

This seems to be what you are trying to do in finder_character . 这似乎是你在finder_character中尝试做的finder_character I'm not sure why you need finder at all. 我不确定你为什么需要finder

In python you can loop over iterables (like strings), so you don't need to do range(len(string)) . 在python中,你可以循环遍历iterables(比如字符串),所以你不需要做range(len(string))

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

There appear to be a few other oddities in your code too: 您的代码中似乎还有一些其他奇怪之处:

  • You open (and iterate through) the file twice, but only closed once. 您打开(并遍历)文件两次,但只关闭一次。
  • line_number is never used line_number从未使用过
  • You get the total of a character in a file for each line in the file, so the total will be vastly inflated. 您将获得文件中每行的字符总数,因此总数将大大增加。

This is probably a much safer version, with open... is generally better than open()... file.close() as you don't need to worry as much about error handling and closing. 这可能是一个更安全的版本, with open...通常比open()... file.close()更好,因为你不需要担心错误处理和关闭。 I've added some comments to help explain what you are trying to do. 我添加了一些评论来帮助解释你想要做什么。

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

If you want to use your original code, you have to pass the filename to the finder() function, and open the file there, for each char you are testing for. 如果要使用原始代码,则必须将文件名传递给finder()函数,并在那里打开文件,以查找要测试的每个字符。

The reason for this is that the file object ( in_file ) is a generator, not a list. 原因是文件对象( in_file )是生成器,而不是列表。 The way a generator works, is that it returns the next item each time you call their next() method. 生成器的工作方式是,每次调用next()方法时它都会返回下一个项目。 When you say 当你说

for line in in_file:

The for ... in statement calls in_file.next() as long as the next() method "returns" (it actually use the keyword yield , but don't think about that for now) a value. 只要next()方法“返回”(它实际上使用关键字yield ,但现在不考虑它in_file.next()for ... in语句调用in_file.next() )一个值。 When the generator doesn't return any values any longer, we say that the generator is exhausted. 当发电机不再返回任何值时,我们说发电机已耗尽。 You can't re-use an exhausted generator. 您无法重复使用耗尽的发电机。 If you want to start over again, you have to make a new generator. 如果你想重新开始,你必须制作一个新的发电机。

I allowed myself to rewrite your code. 我允许自己重写你的代码。 This should give you the desired result. 这应该会给你想要的结果。 If anything is unclear, please ask! 如果有什么不清楚,请询问!

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: 的test.txt:

eeehhh
iii!#
kk ="k
oo o

Output: 输出:

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

If you are having problems understanding the return line, it should be read backwards, like this: 如果您在理解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

If you want to know more about generators, I recommend the Python Wiki page concerning it. 如果您想了解有关生成器的更多信息,我推荐有关它的Python Wiki页面

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM