regex - 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
功能,但似乎无法正确使用语法。
解决方案
您可以通过几种方式做到这一点,其中之一是获取所有 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']
推荐阅读
- mysql - 左连接在多对一关系上重复结果
- python - 在 Manim 中使用“Transform”和“ReplacementTransform”
- android-jetpack-compose - Compose app - 是否可以通过编程方式从 RootView/DecorView 获取组件树信息?
- java - 如何在我的方法中正确使用此 while 循环以使用户重试输入最多 3 次
- python - jupyter notebook:如何设置固定密码并禁用令牌使用?
- java - 测试用例单独运行时通过,一起运行时失败
- python - 在不同的列中获取后续日期
- r - 结合来自 tidyvese 的 sample() 和 group_by()
- android - Google 移动广告 (Admob) - 在测试和生产之间切换?
- python - 在python中遍历带有2个指针变量的链表