0

如果文件包含 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])

但它甚至没有改变甚至没有打印,你会帮助我吗

4

2 回答 2

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
于 2013-09-04T07:59:22.963 回答
-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)
于 2013-09-04T07:41:29.817 回答