Python 如何从给定的txt文件生成词典?
任务:给定一个带有形容词\t同义词、同义词、同义词等的txt文件。在一行中,给出了几行。我需要创建一个字典,其中形容词是一个键,同义词是一个值。我的代码:Python 如何从给定的txt文件生成词典?,python,list,dictionary,findall,Python,List,Dictionary,Findall,任务:给定一个带有形容词\t同义词、同义词、同义词等的txt文件。在一行中,给出了几行。我需要创建一个字典,其中形容词是一个键,同义词是一个值。我的代码: #necessary for command line + regex import sys import re #open file for reading filename = sys.argv[1] infile = open(filename, "r") #a #create a dictionary, wh
#necessary for command line + regex
import sys
import re
#open file for reading
filename = sys.argv[1]
infile = open(filename, "r")
#a
#create a dictionary, where an adjective in a line is a key
#and synonyms are the value
dictionary = {}
#for each line in infile
for line in infile:
#creating a list with keys, a key is everything before the tab
adjectives = re.findall(r"w+\t$", line)
print(adjectives)
#creating a list of values, a value is everything after the tab
synonyms = re.findall(r"^\tw+\n$", line)
print(synonyms)
#combining both lists into a dictionary, where adj are keys, synonyms - values
dictionary = dict(zip(adjectives, synonyms))
print(dictionary)
#close the file
infile.close()
输出显示了空括号。。。是否有人可以帮助修复?使用
split()
使用分隔符拆分字符串,而不是使用正则表达式。首先使用\t
将其拆分,以将形容词与同义词分开,然后使用,
将同义词拆分为一个列表
然后需要在字典中添加一个新键,而不是替换整个字典
for line in infile:
line = line.strip() # remove newline
adjective, synonyms = line.split("\t")
synonyms = synonyms.split(",")
dictionary[adjective] = synonyms
print(dictionary)
关于print(形容词)和print(同义词)调用,您看到一些输出了吗?在正则表达式中,“w”也必须用反斜杠转义。您每次都从头开始重新定义字典,而不是每次都添加一个新键。
dictionary[形容词]=同义词
为什么要使用findall()
获取形容词?每行只有一个形容词,对吗?