【发布时间】:2017-02-14 22:04:15
【问题描述】:
我还在学习python,正在尝试。
我有在文本中搜索单词“Lorem”并用列表中的随机单词替换的代码。这是有效的。
我现在想做的是如何检查列表中的任何单词(words = ['and', 'a', 'is', 'the'])是否在文本中并用另一个列表中的另一个单词替换( t = ['TEXT', 'REPLACE', 'WORD'])。
我想用变量或循环列表替换“Lorem”或用要检查的单词打开 txt 文件。
res = re.sub('Lorem', lambda x: random.choice(t), text)
如果可能的话,如果有人可以告诉我所有 3 个选项:
-循环遍历列表 -多变的 - 打开里面有单词的文件
或者也许还有其他更好的方法?
谢谢!
这里是完整代码
import re
import random
t = ['TEXT', 'REPLACE', 'WORD']
text = '''Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum'''
words = ['and', 'a', 'is', 'the']
res = re.sub('Lorem', lambda x: random.choice(t), text)
print(res)
【问题讨论】:
-
words与t是如何对应的?我们是否假设您只是随机替换为t中的一个词?如果没有,我建议您创建一个字典映射,哪些单词应该替换为某些其他单词。
标签: python python-3.x