从Python中的较大/多行字符串中计算包含两个字符串的*both*的行数

2024-04-19 14:15:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在看这出戏的整个剧本,罗密欧和朱丽叶,我想看看有多少次“罗密欧”和“朱丽叶”在整部戏里出现在同一行<剧中有多少不同的台词同时有“罗密欧”和“朱丽叶”

注:“gbdata”是我的数据名,也就是剧本的整个文本。出于测试目的,我们可以使用:

gbdata = '''
Romeo and Juliet                         # this should count once
Juliet and Romeo, and Romeo, and Juliet  # this also should count once
Romeo                                    # this should not count at all
Juliet                                   # this should not count at all
some other string                        # this should not count at all
'''

正确答案应该是2,因为只有前两行同时包含两个字符串;一行中的更多匹配项不会增加总计数

这就是我目前所做的:

gbdata.count('Romeo' and 'Juliet') # counts 'Juliet's, returning 4

以及

gbdata.count('Romeo') + gbdata.count('Juliet') # combines individual counts, returning 8

如何获得上述测试字符串2的所需输出


Tags: and字符串countnotallthisatreturning
1条回答
网友
1楼 · 发布于 2024-04-19 14:15:03

这里不能使用str.count();它不是为你的目的而建的,因为它没有任何“线”的概念。也就是说,给定一个字符串,您可以通过在换行符'\n'上拆分来将其分解为一个单独行的列表

一个非常简洁的方法可能是:

count = sum((1 if ('Romeo' in l and 'Juliet' in l) else 0) for l in gbdata.split('\n'))

将其扩展为一组单独的命令可能如下所示:

count = 0
for line in gbdata.split('\n'):
    if 'Romeo' in line and 'Juliet' in line:
        count += 1

相关问题 更多 >