簡體   English   中英

從Python中的較大/多行字符串中計算包含兩個字符串的*兩者*的行

[英]Count lines containing *both* of two strings, from a larger/multiline string in Python

我正在看劇本的全部記錄, 羅密歐與朱麗葉 ,我想看看《羅密歐》和《朱麗葉》在整部劇中同一行出現多少次。 又是說,劇本中有多少個不同的詞行都帶有“ Romeo”和“ Juliet”兩個詞?

注意:“ 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的期望輸出?

您不能在這里使用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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM