gpt4 book ai didi

python - 如何从仅包含字符串内容的文本文件简单地填充Python3.2中的字典?

转载 作者:太空宇宙 更新时间:2023-11-03 19:01:59 24 4
gpt4 key购买 nike

如何从仅包含字符串内容的文本文件简单地填充 Python 3.2 中的字典?

我是 Python 新手,我正在尝试从仅包含两列的文本文件构建字典,如下所示:

First_column        second_column
katab perfective active
kutib perfective passive
?aktub imperfective active
?uktab imperfective passive
ka:tib participle active
maktu:b participle passive
The text file contains thousands of lines.

1.我希望first_column下的单词作为“键”,第二个_column下的单词作为“值”,例如

dict = {‘katab’ : ‘perfective_active’, ‘kutib’ : ‘perfective_passive’}

请注意,文本文件包含大量格式和转义字符,例如“”、“\n”和“\t”。所以我不希望这些字符出现在字典中。

  1. 如何将生成的字典写入文件,然后将其导入 Python shell 并搜索给定的键?

这是打印到文本文件的代码:

        import sys
sys.stdout = open("/home/mohammed/seminar/awzan", "a")
print(perfective_active+"\t perfective_active \n")
print(perfective_passive+"\t perfective_passive \n")
print(imperfective_active+"\t imperfective_active \n")
print(imperfective_passive+"\t imperfective_passive \n")
print(participle_active+"\t participle_active \n")
print(participle_passive+"\t participle_passive\n")
sys.stdout.close()

非常感谢您的帮助!

最佳答案

从磁盘文件读取字典:

with open('inputfile.txt') as infile:
d = dict(x.split(None, 1) for x in infile if x.strip())

将字典写入磁盘文件:

with open('outputfile.txt', 'w') as outfile:
outfile.write(''.join(' '.join(x) for x in d.iteritems()))

要搜索特定值:

stuff = d['bother']

关于python - 如何从仅包含字符串内容的文本文件简单地填充Python3.2中的字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15801524/

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