首页 > 解决方案 > Python 正则表达式添加一个“?” 到单词列表中单词的开头

问题描述

#open text file
with open('words') as f:
    for line in f.readlines():
    #pull out all 3 letter words using regular expression and add to wordlist
    word_list += re.findall(r'\b(\w{3})\b', line)

我用它在字典中查找所有 3 个字母的单词。从那里,我想在每个单词的开头添加一个问号。我假设我需要该re.sub功能,但似乎无法正确使用语法。

标签: regexpython-3.x

解决方案


您可以通过几种方式做到这一点,其中之一是获取所有 3 个字母的单词,然后在之后更新它们,否则,您可以按照您正在做的事情进行操作,并随时扩展列表。re.sub如果你想最终建立一个由 3 个字母组成的单词列表,那么这里实际上不需要?

示例words文件:

the quick brown fox called bob jumped over the lazy dog
and went straight to bed
cos bob needed to sleep right now

示例代码:

word_list = []
with open('words') as fin:
    for line in fin:
        matches = re.findall(r'\b(\w{3})\b', line)
        word_list.extend(f'?{word}' for word in matches)

运行后的示例word_list

['?the',
 '?fox',
 '?bob',
 '?the',
 '?dog',
 '?and',
 '?bed',
 '?cos',
 '?bob',
 '?now']

推荐阅读