【问题标题】:String to phrase replacement python字符串到短语替换python
【发布时间】:2017-06-08 12:35:12
【问题描述】:

我有一个文本字符串,我想用一个单词替换两个单词。例如。如果单词是artificial intelligence,我想用artificial_intelligence 替换它。对于 200 个单词的列表和大小为 5 mb 的文本文件,需要执行此操作。 我试过string.replace,但它只适用于一个元素,不适用于列表。

例子

Text='人工智能在深度学习的各种情况下都对我们有用。'

List a : list b
Artificial intelligence: artificial_intelligence
Deep learning: deep_ learning 
...

Text.replace('Artificial intelligence','Artificial_intelligence') 正在工作。 但是

For I in range(len(Lista)):
 Text=Text.replace(Lista[I],List b[I])

没用。

【问题讨论】:

  • 200字看起来不多,你试过用Sublime Text做一个简单的查找/替换吗?
  • 其实我有98个这样的文件..手动更新所有文件太长了:)
  • 好的,但这只是“一次性”替换?如果是这样,我仍然建议您使用 sublime text 并执行 Ctrl + Shift + F 并替换所有出现的地方。
  • @AartikaSethi 为什么不使用正则表达式搜索那个词然后替换它。
  • 什么实际上不起作用?你收到错误信息吗?结果有误吗?

标签: python regex string string-matching


【解决方案1】:

我建议您使用 dict 代替您:

text = "Artificial intelligence is useful for us in every situation of deep learning."
replacements = {"Artificial intelligence" : "Artificial_intelligence",
                "deep learning" : "deep_learning"}

然后您的方法有效(尽管它区分大小写):

>>> for rep in replacements:
        text = text.replace(rep, replacements[rep])
>>> print(text)
Artificial_intelligence is useful for us in every situation of deep_learning.

对于其他方法(如建议的正则表达式方法),请查看SO: Python replace multiple strings

【讨论】:

    【解决方案2】:

    由于您的列表条目和字符串之间存在大小写问题,您可以使用带有IGNORECASE 标志的re.sub() 函数来获得您想要的:

    import re
    
    list_a = ['Artificial intelligence', 'Deep learning']
    list_b = ['artificial_intelligence', 'deep_learning']
    text = 'Artificial intelligence is useful for us in every situation of deep learning.'
    
    for from_, to in zip(list_a, list_b):
        text = re.sub(from_, to, text, flags=re.IGNORECASE)
    
    print(text)
    # artificial_intelligence is useful for us in every situation of deep_learning.
    

    注意zip() 函数的使用,它允许同时遍历两个列表。


    还要注意 Christian 是对的,dict 会更适合您的替换数据。对于完全相同的结果,前面的代码将如下所示:

    import re
    
    subs = {'Artificial intelligence': 'artificial_intelligence',
            'Deep learning': 'deep_learning'}
    text = 'Artificial intelligence is useful for us in every situation of deep learning.'
    
    for from_, to in subs.items():
        text = re.sub(from_, to, text, flags=re.IGNORECASE)
    
    print(text)
    

    【讨论】:

      猜你喜欢
      • 2021-02-02
      • 1970-01-01
      • 1970-01-01
      • 2014-05-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多