我有一个字符串列表,每个字符串大约有 10 个句子。我希望找到每个字符串中以大写字母开头的所有单词。最好在句子的第一个单词之后。我正在使用 re.findall 来执行此操作。当我手动设置 string = '' 时,我没有遇到任何问题,但是当我尝试使用 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 个项目中每一项的输出。有什么想法吗?
最佳答案
最简单的方法是编写一个 for
循环来检查列表元素的第一个字母是否大写。如果是,它将被附加到输出
列表中。
output = []
for i in list_3:
if i[0] == i[0].upper():
output.append(i)
print(output)
我们还可以使用列表理解并在一行中完成。我们还检查元素的第一个字母是否是大写字母。
output = [x for x in list_3 if x[0].upper() == x[0]]
print(output)
编辑
您想将句子作为列表的元素,所以这里是解决方案。我们迭代 list_3
,然后使用 split()
函数迭代每个单词。然后我们检查该单词是否大写。如果是,则将其添加到输出
。
list_3 = ["Remember your college application process? The tedious Common App applications, hours upon hours of research, ACT/SAT, FAFSA, visiting schools, etc. Do you remember who helped you through this process? Your family and guidance counselors perhaps, maybe your peers or you may have received little to no help"]
output = []
for i in list_3:
for j in i.split():
if j[0].isupper():
output.append(j)
print(output)
关于python - 对于列表中的多个字符串,如何查找字符串中以大写字母开头的所有单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62957262/