2

我正在尝试通过将其中使用的缩写替换为其实际的短语等价来规范化字符串。我在名为“dict”的python字典中有一个这样的缩写列表。例如:

print dict['gf']

会导致:

girlfriend

现在,我的问题是,由于这本字典中有大约 300 个键,我需要一种快速的方法来检查这些键中是否有任何一个出现在给定的字符串中。我最初的想法是使用下面的正则表达式,然后以某种方式尝试检查并比较字典的所有键与给定字符串中的所有单词(我在下面的代码中将其命名为“文本”),但我注意到我不能将变量放在字符串的中间。

import re
text = "I have a gf"
print re.sub (r'(?<![a-zA-Z])(gf)(?![a-zA-Z])', 'girlfriend', text)

这将打印:

I have a girlfriend

但正如您所注意到的,我不能将这种方法应用于上述情况。谁能帮我这个?提前致谢!

4

2 回答 2

2

您可以使用.get()字典上的方法来查找缩写。返回的默认值.get()None,但您可以提供一个参数以在查找失败时使用。所以在字典中.get(s, s)查找,如果它不在字典中则s返回不变,如果它在则返回字典值。s

然后只需拆分字符串并查找每个单词并重新加入。

abbrevs = { "gf" : "girlfriend", "cul" : "see you later" }

def lookup(s):
    return abbrevs.get(s, s)

def expand(s_text):
    return ' '.join(lookup(s) for s in s_text.split())

print(expand("My gf just called.  cul"))

以上仅在空白处拆分单词,并将所有空白替换为单个空格。您可以编写一个匹配空格和/或标点符号的正则表达式,并使用它来制作更智能的拆分功能,并且您可以保存匹配的空格以使其不会用单个空格替换所有空格。但我想让这个例子保持简单。

于 2012-12-25T07:36:20.083 回答
2

这是一种构造正则表达式以一次匹配所有单词的方法:

words = {
    'gf': 'girlfriend',
    'bf': 'boyfriend',
    'btw': 'by the way',
    'hi': 'hello',
}

pat = re.compile(r"\b(%s)\b" % "|".join(words))

text = "The gf and the bf say hi btw."

new_text = pat.sub(lambda m: words.get(m.group()), text)

print new_text

印刷:

The girlfriend and the boyfriend say hello by the way.
于 2012-12-25T12:00:14.023 回答