Python 填充字典(来自不规则的模式文本)
我是一名编程初学者,作业中有一个问题。 对于给定的txt文件,采用以下格式,我假设将它们组织成两个字典Python 填充字典(来自不规则的模式文本),python,dictionary,Python,Dictionary,我是一名编程初学者,作业中有一个问题。 对于给定的txt文件,采用以下格式,我假设将它们组织成两个字典 last name, first name network last name, first name last name, first name last name, first name network last name, first name last name, first name last name, first name last name, first name last
last name, first name
network
last name, first name
last name, first name
last name, first name
network
last name, first name
last name, first name
last name, first name
last name, first name
last name, first name
last name, first name
network
last name, first name
每个区块的第一个名称是概要文件的名称(person)
下面剩下的名字都是profile的朋友。
(每个区块的第一行始终是概要文件的名称,第一个名称可能有多个单词,网络中永远不会有逗号)
每个外形都有不规则的线条,有些外形有网络,有些则没有
我被要求创建两个字典,person-to-friends(以person为键,friends to-values)和person-to-network(以person为键,networks to-values)
结果应该如下所示
个人对朋友:{'Jay Pritchett':['Gloria Pritchett','Manny Delgado','Claire Dunphy','Claire Dunphy':['Phil Dunphy','Mitchell Pritchett','Jay Pritchett','Manny Delgado':['Gloria Pritchett','Jay Pritchett','Luke Dunphy']
个人对网络:{'Phil Dunphy':['Real Estate Association'],'Claire Dunphy':['Parent Teacher Association'],'Manny Delgado':['Chess Club'],'Mitchell Pritchett':['Law Association']}
我在编写告诉python填充字典的代码时遇到困难。
[person]的常见模式可能是它总是空行之后的一行。但是,第一个[person]位于文件的开头,因此前面没有空行。。
我遇到了一个问题,如果我使用for循环,那么自从我尝试将
person = line
在开始时要考虑到一个事实,即名字前面没有空行
我曾尝试使用readlines和readline两种方法,但每种方法都有问题。我想知道你们是否能帮我。谢谢大家! 遇到非空行时,需要根据前一行是否为空来处理。处理文件中的第一行时,就好像它前面有一个空格一样。对吗 创建一个布尔变量以跟踪上一行何时为空。类似这样的内容(假设文件已打开并准备好读取):
这不是一个完整的答案,我没有任何python经验。。。但这个伪代码可能会有帮助:
您需要显示一些代码,否则这只是为您自己完成任务;)
was_blank = True
for line in file:
if line: # evaluates True if the line is not blank.
if was_blank:
new_name(line)
else:
process_the_line(line)
was_blank = False
else:
was_blank = True
def get_groups(lines):
group = []
for line in lines:
line = line.strip()
if line:
group.append(line)
else:
if group:
yield group
group = []
if group:
yield group
with open("myfile.txt") as inf:
for group in get_groups(inf):
# now process group!