【发布时间】:2020-03-02 15:12:49
【问题描述】:
我想使用 Python 替换 CSV 或 Excel 文件中的字符串。我的代码运行但我有一个问题,如果我有类似的东西:
将“rechts”替换为“right”,将“rechts schiebend”替换为“right push”
替换不会查找整个单元格值并将每个“rechts”转换为“right”,然后查找“rechts schiebend”并且找不到它了。
有没有办法像在 Excel 中一样查找整个单元格字符串?
这是我目前使用的代码:
import csv
reps = {
'rechts' : 'right',
'rechts schiebend' : 'right pushing'}
def replace_all(text, dic):
for i, j in reps.items():
text = text.replace(i, j)
return text
with open('Test.csv','r') as f:
text=f.read()
text=replace_all(text,reps)
with open('Test_en.csv','w') as w:
w.write(text)
【问题讨论】:
-
分别查找和替换
rechts和schiebend怎么样? -
可以在这个小例子中使用,但不适用于整个 CSV,因为这会导致一些奇怪的翻译。
-
您能否在问题中包含其他一些示例?
-
@mk1337:将
'rechts schiebend' : 'right pushing'}替换为'schiebend' : 'pushing'}意味着避免使用sentences 和double 字词。如果您需要 sentences 在 singences 之前运行所有 sentences。 -
我一开始就按照你的建议做了,现在使用熊猫。非常感谢大家!
标签: python excel python-3.x csv replace