gpt4 book ai didi

python - 使用带有嵌套 while 循环的 readline 方法时出现问题 Python

转载 作者:太空宇宙 更新时间:2023-11-03 18:02:22 25 4
gpt4 key购买 nike

我正在尝试编写一个代码,该代码将采用包含单词及其定义的 .txt 文件并生成 {'word1':['definition1', 'definition2'...]} 的字典。 .txt 文件采用以下格式:

单词1

定义1

定义2

(空行)

单词2

定义1

定义2...

到目前为止我编写的函数体如下:

line = definition_file.readline()
dictx = {}

while line != '':
key = line.strip()
defs = []
line = definition_file.readline()
while line != '\n':
defx = [line.strip()]
defs += defx
line = definition_file.readline()
if key not in dictx:
dictx[key] = defs

return dictx

我很快意识到这段代码的问题是它只会返回一个包含第一个单词的字典。我需要一种方法来使代码循环,以便它返回包含所有单词+定义的字典。我希望不使用中断就能做到这一点。

谢谢!

最佳答案

这应该可以做到:

from collections import defaultdict

d = defaultdict(list)
is_definition = False

with open('test.txt') as f:
for line in f:
line = line.strip().rstrip('\n')
if line == '': # blank line
is_definition=False
continue
if is_definition: # definition line
d[word].append(line)
else: # word line
word = line
is_definition = True

关于python - 使用带有嵌套 while 循环的 readline 方法时出现问题 Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27474688/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com