替换文件python中的值

时间:2013-09-04 07:28:48

标签: python python-3.x

如果文件包含A 2 B 3,如果它包含值为2和3的A或B,则必须替换用户输入,(例如:香蕉应该变为2香蕉)到目前为止,我已经这样做了:

word=input("Enter string: ")
word=list(word)
with open('mapping.txt') as f:
 key = {}
  for line in f:
   first, second = line.split()
   key[first] = second
    for i in word:
     if first in i:
      word=word.replace(i,key[i])

但即使打印也没有改变,请你帮助我

2 个答案:

答案 0 :(得分:1)

它不起作用的原因是因为每次阅读mapping.txt文件时,都会创建字典,同时检查替换字。因此,映射的第一行将在字典中创建一个项目,然后根据字符串检查一个项目。

你也不打印任何东西。

您需要创建一次映射,然后检查整个字典,如下所示:

mapping = {}
with open('mapping.txt') as f:
    for line in f:
        word, replacement = line.split()
        mapping[word.strip()] = replacement.strip()

user_input = input("Enter string: ")

new_line = ' '.join(mapping.get(word, word) for word in user_input.split())

print(new_line)

当你运行它时,这就是你将得到的:

Enter string: this is A string with a B
this is 2 string with a 3

答案 1 :(得分:-1)

我认为这应该有效:

#!/usr/local/bin/python3
word=input("Enter string: ")
with open('input.txt') as f:
  key = {}
  for line in f:
    first, second = line.split()
    key[first] = second
for replacement in key:
    word=word.replace(replacement,key[replacement])

print(word)