python - 将字典中的值转换为键

标签 python python-2.7 python-3.x

我有一个包含以下文本的 txt 文件:

water=45 
melon=8 
apple=35 
pineapple=67 
I=43 
to=90 
eat=12 
tastes=100 
sweet=21 
it=80 
watermelon=98 
want=70

我还有另一个文件,其中包含以下文本:

I want to eat watermelon
it tastes sweet pineapple

我想输出到:

I want to eat watermelon = 43,70,90,12,98
it tastes sweet pineapple = 80,100,21,67

这是我到目前为止所拥有的:

import nltk 
f = open(r'C:\folder\dic\file.txt','r')
answer = {}
for line in f:
     k, v = line.strip().split('=')
     answer[k.strip()] = v.strip()

f.close()

print answer.values()

h = open(r'C:\folder\dic\file2.txt','r')
raw=h.read()
tokens = nltk.sent_tokenize(raw)
text = nltk.Text(tokens)


for line in text:
    word = line
    for value in answer.values():
        if value == word:
            word=answer[keys]
        else:
            word="not found"

 print word

在 Python 中执行此操作的最佳方法是什么?

最佳答案

请检查此代码。

import re
f = open(r'C:\Users\dinesh_pundkar\Desktop\val.txt','r')
val_dict = {}
for line in f:
     k, v = line.strip().split('=')
     val_dict[k.strip()] = v.strip()
f.close()

print val_dict

h = open(r'C:\Users\dinesh_pundkar\Desktop\str_txt.txt','r')
str_list = []
for line in h:
     str_list.append(str(line).strip())

print str_list

tmp_str = ''
for val in str_list:
    tmp_str = val 
    for k in val_dict.keys():
            if k in val:
                replace_str = str(val_dict[k]).strip() + ","
                tmp_str= re.sub(r'\b{0}\b'.format(k),replace_str,tmp_str,flags=re.IGNORECASE)

    tmp_str = tmp_str.strip(",")
    print val, " = ", tmp_str
    tmp_str = ''

输出:

C:\Users\dinesh_pundkar\Desktop>python demo.py
{'apple': '35', 'I': '43', 'sweet': '21', 'it': '80', 'water': '45', 'to': '90',
 'taste': '100', 'watermelon': '98', 'want': '70', 'pineapple': '67', 'melon': '
8', 'eat': '12'}
['I want to eat watermelon', 'it taste sweet pineapple']
I want to eat watermelon  =  43, 70, 90, 12, 98
it taste sweet pineapple  =  80, 100, 21, 67

关于python - 将字典中的值转换为键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39057167/

相关文章:

python - 终端在 VS Code 中仅显示一个空的不可编辑光标

python - 还有其他方法可以连接到 Airflow 中的 Google 表格吗?

python - 删除连续的重复项。离开中间

python - 在 Windows 8 (x64) 中安装 PyOpenCL "fatal error: CL/cl.h: No such file or directory"错误

python - 为什么 Python 优化了 "if 0"而不是 "if None"?

python - 添加字典值的元素

python - 在python中复制对象时如何跳过初始化?

python - 根据原始数据框列数创建多个数据框

python - 从字符串字符递归构建字典

python - pipfile 可编辑包位置