繁体   English   中英

使用字典更改字符串中的单词。 蟒蛇

[英]Changing words in a string using dictionary. python

我有以下消息:

msg = "Cowlishaw Street & Athllon Drive, Greenway now free of obstruction."

我想将“ Drive”更改为“ Dr”或将“ Street”更改为“ St”

expected_msg = "Cowlishaw St and Athllon Dr Greenway now free of obstruction"

我也有一个“转换功能”

如果有这样的单词,我该如何检查列表。 如果是这样,请使用“转换”功能对其进行更改。 “转换”是具有单词(例如“ Drive”)作为键且值是“ Dr”的字典

这就是我所做的

def convert_message(msg, conversion):
    msg = msg.translate({ord(i): None for i in ".,"})
    tokens = msg.strip().split(" ")
    for x in msg:
         if x in keys (conversion):


    return " ".join(tokens)

这不是简单的:

translations = {'Drive': 'Dr'}

for index, token in enumerate(tokens):
    if token in conversion:
        tokens[index] = conversion[token]

return ' '.join(tokens)

但是,这对"Obstruction on Cowlishaw Street."句子"Obstruction on Cowlishaw Street." 因为令牌现在是Street. 也许您应该对re.sub使用正则表达式:

import re
def convert_message(msg, conversion):
    def translate(match):
        word = match.group(0)
        if word in conversion:
            return conversion[word]
        return word

    return re.sub(r'\w+', translate, msg)

在这里re.sub找到1个或多个连续的( + )字母数字字符( \\w ); 并且对于每个这样的正则表达式match调用给定的函数,将匹配项作为参数; 可以使用match.group(0)检索匹配的单词。 该函数应返回给定匹配项的替换项-在此,如果在字典中找到了该单词,则返回该单词,否则返回原始单词。

从而:

>>> msg = "Cowlishaw Street & Athllon Drive, Greenway now free of obstruction."
>>> convert_message(msg, {'Drive': 'Dr', 'Street': 'St'})
'Cowlishaw St & Athllon Dr, Greenway now free of obstruction.'

至于& ,在Python 3.4+上,您应该使用html.unescape解码HTML实体:

>>> import html
>>> html.unescape('Cowlishaw Street & Athllon Drive, Greenway now free of obstruction.')
'Cowlishaw Street & Athllon Drive, Greenway now free of obstruction.'

这将照顾所有已知的HTML实体。 对于较旧的python版本,您可以在此问题上找到替代方法

正则表达式与&字符不匹配; 如果您也想替换它,我们可以使用正则表达式\\w+|. 意思是:“任何连续的字母数字字符运行,或者然后是不在此运行中的任何单个字符”:

import re
import html


def convert_message(msg, conversion):
    msg = html.unescape(msg)

    def translate(match):
        word = match.group(0)
        if word in conversion:
            return conversion[word]
        return word

    return re.sub(r'\w+|.', translate, msg)

那你可以做

>>> msg = 'Cowlishaw Street & Athllon Drive, Greenway now free of obstruction.'
>>> convert_message(msg, {'Drive': 'Dr', '&': 'and', 
                          'Street': 'St', '.': '', ',': ''})
'Cowlishaw St and Athllon Dr Greenway now free of obstruction'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM