【问题标题】:How to replace string in Excel and check whole cell string?如何在 Excel 中替换字符串并检查整个单元格字符串?
【发布时间】: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


【解决方案1】:

您可以将 csv 转换为 pandas.DataFrame 并使用 applymap() 转换所有值。

import pandas as pd

test = pd.read_csv("Test.csv")

reps = {
    'rechts': 'right',
    'rechts schiebend': 'right pushing'
}
translator = lambda x: reps[x] if x in reps else x
modified_test = test.applymap(translator)
modified_test.to_csv('Test_en.csv', index=None) # save result

【讨论】:

    【解决方案2】:

    你可以试试这个解决方案:

    import re
    csv = 'rechts,rechts schiebend,schiebend,schiebend rechts'
    
    reps = {
        'rechts' : 'right',
        'rechts schiebend' : 'right pushing'
    }
    
    cells = csv.split(',')
    
    for idx, cell in enumerate(cells):
        if cell in reps:
            cells[idx] = re.sub(re.compile('^' + cell + '$'), reps[cell], cell)
    
    csv = ','.join(cells)
    
    print(csv)
    

    它应该将 csv 更新为

    right,right pushing,schiebend,schiebend rechts
    
    

    【讨论】:

      猜你喜欢
      • 2021-02-11
      • 2015-10-02
      • 1970-01-01
      • 2015-09-09
      • 2020-04-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-15
      相关资源
      最近更新 更多