用另一个列表中的词替换出现在文本中的列表中的词

2024-03-29 09:19:52 发布

您现在位置:Python中文网/ 问答频道 /正文

position_list = ['front', 'frnt', 'ft', 'back', 'bck', 'behind', 'right', 'rhs']

position = ['down', 'right', 'inner', 'front', 'top', 'back', 'left']

这是我用PYTHON编写的两个列表。 对于给定的文本,如果出现位置\列表中的任何单词,则必须将其替换为位置中的特定单词。你知道吗

即文字为:“frnt轮胎和bck轮胎磨损”

“frnt”和“bck”必须分别替换为“front”和“back”。你知道吗

我使用的python代码是:

if wrong == 'frnt' or wrong == 'ft':

结构=结构更换(错,'front')

if wrong == 'bck' or wrong == 'behind':

结构=结构更换(错,'回来')

但我正在寻找python代码,它直接使用这些列表替换单词。你知道吗


Tags: 代码right列表ifbackposition单词结构
3条回答

我想是的尾撑更换()方法,(可能)将替换不希望替换的子字符串,如@oleg所示

我知道这不是一个更干净的方法,但也许使用字典和.split()和.join()会有所帮助。你知道吗

s = 'the frt bck behind'
l = s.split()
new =[]
d ={'frt':'front','behind':'back','bck':'back'}
for word in l:
    if word in d:
        new.append(d[word])
    else:new.append(word)    
print " ".join(new)
>>> the front back back

我想大写、小写和标点符号都会有问题,但用几个字母就很容易解决了字符串.替换()秒

我真的不明白你在这两个列表的结构。这还不清楚,我不认为你能从中得到一个合适的算法。你知道吗

你说:“对于一个给定的文本,如果位置列表中的任何一个单词出现,它必须被位置中的特定单词替换”,这意味着“”必须被“”、“”被“”替换,“”没有替换。那没道理!你知道吗

所以我猜,从你剩下的问题来看,你想把“front”后面的词替换成“front”,把“back”后面的词替换成“back”。但是,没有信息可以帮助算法知道哪些词是替换词,哪些词要被替换。你知道吗

因此,唯一的解决方案是以一种更具python风格的方式改变你的结构,从中生成一个简单而优雅的算法。然后,您可能需要尝试这样的结构:

position = ['front', 'back']
position_list = [('frnt', 'ft'), ('bck')]

然后算法看起来像:

replaces = zip(position, position_list)
for new_word, old_words in replaces:
    for old_word in old_words:
        str = str.replace(old_word, new_word)

您也可以使用字典:

positions = {'front': ['frnt', 'ft'], 'back': ['bck']}
for new_word, old_words in positions.iteritems():
    for old_word in old_words:
        str = str.replace(old_word, new_word)

换句话说,尽量避免创建最终会导致生成处理列表索引的算法的结构。。。你知道吗

您需要在两个列表之间进行某种映射,否则您无法找出用什么替换什么。你可以用口述:

t = 'The frnt tyre'

words = {
    'front': ('frnt', 'frt'),
}

for word, repl in words.items():
    for r in repl:
        t = t.replace(r, word)

print t

结果:

The front tyre

相关问题 更多 >