我有一个字符串列表,每个字符串大约有10个句子。我希望从每个字符串中找到以大写字母开头的所有单词。最好在句子的第一个单词之后。我用re.findall来做这个。当我手动设置字符串=“”时,这样做没有问题,但是当我尝试使用for循环在列表中的每个条目上循环时,我会得到不同的输出
for i in list_3:
string = i
test = re.findall(r"(\b[A-Z][a-z]*\b)", string)
print(test)
输出:
['I', 'I', 'As', 'I', 'University', 'Illinois', 'It', 'To', 'It', 'I', 'One', 'Manu', 'I', 'I', 'Once', 'And', 'Through', 'I', 'I', 'Most', 'Its', 'The', 'I', 'That', 'I', 'I', 'I', 'I', 'I', 'I']
当我手动输入字符串值时
txt = 0
for i in list_3:
string = list_3[txt]
test = re.findall(r"(\b[A-Z][a-z]*\b)", string)
print(test)
输出:
['Remember', 'The', 'Common', 'App', 'Do', 'Your', 'Often', 'We', 'Monica', 'Lannom', 'Co', 'Founder', 'Campus', 'Ventures', 'One', 'Break', 'Campus', 'Ventures', 'Universities', 'Undermatching', 'Stanford', 'Yale', 'Undermatching', 'What', 'A', 'Yale', 'Lannom', 'There', 'During', 'Some', 'The', 'Lannom', 'That', 'It', 'Lannom', 'Institutions', 'University', 'Chicago', 'Boston', 'College', 'These', 'Students', 'If', 'Lannom', 'Recruiting', 'Elite', 'Campus', 'Ventures', 'Understanding', 'Campus', 'Ventures', 'The', 'For', 'Lannom', 'What', 'I', 'Wish', 'I', 'Knew', 'Before', 'Starting', 'Company', 'I', 'Even', 'I', 'Lannom', 'The', 'There']
但我似乎无法编写一个for循环来正确打印列表中5项的输出。有什么想法吗
假设句子由一个空格分隔,您可以将
re.findall
与以下正则表达式一起使用Start your engine!Python code
Python的正则表达式引擎执行以下操作
如果句子可以用一个或两个空格分隔,则在
(?<![.?!] )
之后插入否定的lookbehind(?<![.?!] )
如果使用PyPI regex模块,则可以使用可变长度lookback
(?<![.?!] +)
最简单的方法是编写
for
循环,检查列表元素的第一个字母是否大写。如果是,它将被附加到output
列表中我们也可以使用列表理解,并在一行中完成。我们还检查元素的第一个字母是否大写
编辑
您希望将句子作为列表的一个元素,因此下面是解决方案。我们迭代
list_3
,然后使用split()
函数迭代每个单词。然后我们检查这个词是否大写。如果是,则将其添加到output
据我所知,你们有如下清单:
您正在对列表进行迭代,但每次迭代都会覆盖
test
变量,因此结果不正确。您必须在附加变量中累积结果,或在每次迭代中立即打印:或
至于regexp,它忽略了句子中的第一个单词,您可以使用
(?<!\A)
-不是字符串的开头(?<!\.)
-不是点后的第一个单词\s+
-点后的可选空格李>您将收到可能以空格作为前缀的单词,下面是最后一个示例:
相关问题 更多 >
编程相关推荐