【问题标题】:How to convert text into a dictionary in Python如何在 Python 中将文本转换为字典
【发布时间】:2014-12-03 14:37:23
【问题描述】:

我有一个文本文件要打开并变成字典,如下所示:

文本文件中的文本:

“在过去十年中,人们对爬行动物哺乳动物的兴趣几乎没有下降。”

转换成字典:

{'during' : 'the', 'the' : 'last', 'last' : 'ten', 'ten' : 'years', 'years' : 'the' ...etc }

这样文本文件中的每个单词都会变成一个键,后面的单词是它的值。

我目前的代码是这样的:

def makedict():
    with open('textfile.txt') as f:
        d = dict(line.strip().split(None, 1) for line in f)
        return d
print(makedict())

但是当我运行它时,它会打印出第一个单词作为键,其余的作为值,如下所示:

{ 在 : '过去十年中,对爬行动物哺乳动物的兴趣下降几乎没有引起注意。' }

【问题讨论】:

  • 您的makedict 函数不会返回它创建的d 结果,这实际上与返回None 相同。
  • 我现在试过了,它仍然没有达到我想要的效果
  • 这将如何处理重复键?您最终将拥有多个值的相同键。

标签: python file text dictionary text-files


【解决方案1】:
def makedict():
    with open('textfile.txt') as f:
        words = [i.strip().lower() for i in f.read().split()]
        return dict(zip(words[:-1], words[1:]))

>>> makedict()
{'mammals': 'has', 'last': 'ten', 'been': 'barely', 'ten': 'years,', 'during': 'the', 'decrease': 'in', 'interest': 'in', 'reptilian': 'mammals', 'barely': 'noticeable.', 'has': 'been', 'the': 'decrease', 'years,': 'the', 'in': 'reptilian'}

注意:字典只能有唯一的键。这意味着如果您有重复的单词,则结果字典中只有最近的值,因为所有以前的值都会被覆盖。

例如注意字典只有

{'the': 'decrease'}

代替

{'the': 'last', 'the': 'decrease'}

因为你不能有重复的键

我不确定您打算如何使用这本词典,但请记住这一点。

【讨论】:

  • 我认为他希望键是以前的值,所以他希望每个单词都是键
  • 这正是它的作用。但是,我注意到关于重复键的警告。
【解决方案2】:
dic={}

p="During the last ten years, the decrease in interest in reptilian mammals has been barely noticeable"


x=zip(p.split(),p.split()[1:])
for k,y in x:
    dic[k]=y
print dic

【讨论】:

    【解决方案3】:

    如果您有重复的键,您应该将值附加到列表中,您还需要使用一些东西来去除逗号等:

    from collections import defaultdict
    spl = p.split()
    d = defaultdict(list)
    for a,b in zip(spl, spl[1:]):
        d[a.translate(None,".,")].append(b.translate(None,".,"))
    print(d)
    
    defaultdict(<type 'list'>, {'last': ['ten'], 'ten': ['years'], 'reptilian': ['mammals'], 'barely': ['noticeable'], 'mammals': ['has'], 'years': ['the'], 'decrease': ['in'], 'been': ['barely'], 'interest': ['in'], 'in': ['interest', 'reptilian'], 'During': ['the'], 'the': ['last', 'decrease'], 'has': ['been']})
    

    【讨论】:

      猜你喜欢
      • 2016-10-31
      • 2020-09-24
      • 2020-12-16
      • 2023-03-15
      • 2020-11-24
      • 1970-01-01
      • 2021-12-18
      • 2020-07-22
      相关资源
      最近更新 更多