【问题标题】:Replace strings in a dictionary with integers (from a text file)用整数替换字典中的字符串(来自文本文件)
【发布时间】:2021-12-24 16:49:44
【问题描述】:

我有来自文本文件的值(这是情绪:“消极”、“中立”、“积极”)。关键是形容词。我想生成一个包含形容词和新值的字典,即 -1、0、1。

这是我目前制作的:

dictionary = {} #creating an empty dictionary
infile =  open('adjective_sentiment.txt', 'r')
for line in infile:
  key, value = line.split()
  dictionary[key] = value
  print(dictionary)

如何访问这些值并用数字替换它们?

【问题讨论】:

  • 请添加“adjective_sentiment.txt”文件的样本
  • 我的意思是问题,而不是评论

标签: python string dictionary integer


【解决方案1】:

你可以这样做:

D = {'negative': -1, 'neutral': 0, 'positive': 1}
dictionary = dict()
with open('adjective_sentiment.txt') as infile:
    for line in infile:
        a, s = line.split()
        dictionary[a] = D[s]
print(dictionary)

当然,如果文件的格式没有完全按照说明进行

【讨论】:

    猜你喜欢
    • 2021-11-18
    • 1970-01-01
    • 1970-01-01
    • 2016-10-02
    • 1970-01-01
    • 2019-05-24
    • 1970-01-01
    • 1970-01-01
    • 2022-07-12
    相关资源
    最近更新 更多