简体   繁体   English

python读取文件无限循环

[英]python reading file infinite loop

pronunciation_file = open('dictionary.txt')
pronunciation = {}
line = pronunciation_file.readline()
while line != '':
    n_line = line.strip().split(' ' , 1)
    pronunciation[n_line[0]] = n_line[1].strip()
    line = pronunciation_file.readline()
print(pronunciation)

the code is to turn a file of words and its pronunciation into a dictionary (keys are words and value is pronunciation) for example 'A AH0\\n...' into {'A':'AH0'...} the problem is if I put the print inside the loop, it prints normal(but it prints all the unfinished dictionaries) however if i put the print outside the loop like the one above, the shell returns nothing and when i close it ,it prompts the program is still running(where is probably a infinite loop) 代码是将单词及其发音的文件转换成字典(键是单词,值是发音),例如将'A AH0 \\ n ...'变成{'A':'AH0'...}问题是如果我将打印内容放入循环中,它会正常打印(但它会打印所有未完成的字典),但是如果我将打印内容像上面的一样放在循环外面,则外壳什么也不会返回,当我关闭它时,它会提示程序仍在运行(可能是无限循环)

Help please 请帮助

I also tried cutting out first few hundred words and run the program, it works for very short files but it starts returning nothing at a certain length:| 我还尝试切出前几百个单词并运行该程序,该程序适用于非常短的文件,但在一定长度下它什么也开始不返回:|

That is not how to read from a file: 那不是从文件中读取的方法:

# with will also close your file
with open(your_file) as f:
    # iterate over file object
    for line in f:
         # unpack key/value for your dict and use rstrip
         k, v = line.rstrip().split(' ' , 1)
         pronunciation[k] = v

You simply open the file and iterate over the file object. 您只需打开文件并遍历文件对象即可。 Use .rstrip() if you want to remove from the end of string, there is also no need to call strip twice on the same line. 如果要从字符串末尾删除,请使用.rstrip() ,也无需在同一行上两次调用strip。

You can also simplify your code to just using dict and a generator expression 您还可以将代码简化为仅使用dict生成器表达式

with open("dictionary.txt") as f:
    pronunciation = dict(line.rstrip().split(" ",1) for line in f)

Not tested, but if you want to use a while loop, the idiom is more like this: 未经测试,但是如果您想使用while循环,则该习惯用法更像这样:

pronunciation={}
with open(fn) as f:
    while True:
        line=f.readline()
        if not line:
            break
        l, r=line.split(' ', 1)    
        pronunciation[l]=r.strip()

But the more modern Python idiom for reading a file line-by-line is to use a for loop as Padraic Cunningham's answer uses. 但是,逐行读取文件的更现代的Python习惯用法是使用Padraic Cunningham的答案所使用的for循环。 A while loop is more commonly used to read a binary file fixed chunk by fixed chunk in Python. while循环更常用于在Python中按固定块读取二进制文件固定块。

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

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