【问题标题】:Replacing text according to list [closed]根据列表替换文本[关闭]
【发布时间】:2013-11-01 08:51:47
【问题描述】:

我在文件中有文本,如下所示:

美联储可能要等到 2014 年初才开始宽松的原因之一 回到刺激措施是那里的政策制定者根本不会 知道在那之前劳动力市场是增强还是减弱。 直到 12 月,月度就业调查才会免于 关闭静态,并且该报告直到早期才出来 一月。

9 月就业报告令人失望,经济增长 148,000 个新工作岗位,而不是预期的 185,000 个,但股票上涨 预计美联储的刺激措施将持续到 2014 年。

在另一个文件我有替换列表:

一月:二月 九月:十一月 每月:每周

如何根据替换列表替换文本中的所有单词?

Try this:
with open('t_.txt') as f3:
    with open ('egb.out') as w3:

        for line in f3:
            for line1 in w3:

                word,string = line1.split(':')
                print line.replace(word,string),

但只适用于第一行

【问题讨论】:

  • 我认为这些可怕的拼写错误是故意的?

标签: python text replace


【解决方案1】:

使用字典和类似字符串的东西(或从文件中读取,或其他):

rep = {'January':'Febryary', 'September':'november', 'monthly':'weekly'}

s = """One reason the Fed is likely to wait until early 2014 to begin easing back on stimulus efforts is that policy makers there simply will not know if the labor market is gaining or losing strength before then. Not until December will the monthly jobs survey be free of the shutdown static, and that report does not come out until early January.

The September jobs report was disappointing, with the economy adding 148,000 new jobs instead of the expected 185,000, but stocks rose on anticipation that Fed stimulus efforts would continue well into 2014."""

然后你可以使用这个单行:

result = reduce(lambda x, y: x.replace(*y), rep.iteritems(), s)

或者使用(在我看来更有效的)正则表达式:

import re

rep = dict((re.escape(k), v) for k, v in rep.iteritems()) # makes sure things wont screw up
pattern = re.compile("|".join(rep.keys())) # create the pattern
result = pattern.sub(lambda m: rep[re.escape(m.group(0))], s)

但实际上,如果你正在处理这样的事情,你应该看看nltk (Natural Language Toolkit)

【讨论】:

    【解决方案2】:

    在您将这两个文件读入字符串后,这些内容应该可以工作

    # text contains the first file
    # replacements contains the list of replacement
    for w in replacements.split(' '):
        if ':' in w:
            word,replacement = w.split(':')
            text = text.replace(word,replacement)
    

    【讨论】:

    • 这不会考虑以标点符号结尾/开头的单词(如 , 和 .)。
    • word,replacement = w.split(':') ValueError: need more than 1 value to unpack
    • 你能显示你使用的替换字符串吗?可能有额外的空格。尝试在循环之前添加replacement = replacement.strip()
    • 为什么会这样,米歇尔?已经很晚了,所以很可能我忽略了一些东西。
    • with open('t1.txt') as f3: with open ('t2.txt') as w3: for line in f3: for line1 in w3: word,string = line1.split(':') print line.replace(word,string), 试试这个,但只做第一行
    猜你喜欢
    • 2020-12-17
    • 2021-05-14
    • 1970-01-01
    • 2012-07-25
    • 1970-01-01
    • 2021-12-25
    • 1970-01-01
    • 2022-09-30
    • 1970-01-01
    相关资源
    最近更新 更多