尝试基于子字符串打印文本文件中的行

2024-09-29 00:22:54 发布

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

我知道在《罗密欧与朱丽叶》这出戏里有五行,其中一行既有“朱丽叶”又有“罗密欧”。我想把《罗密欧与朱丽叶》中的台词印出来,剧中有“朱丽叶”和“罗密欧”两个词。你知道吗

到目前为止,我试着:

pattern = 'Romeo and Juliet'
matching_lines = [line for line in open('Romeo and Juliet.txt').readlines() if pattern in line]
print(matching_lines)

但它只打印:

['Romeo and Juliet\n']

而不是剧中既有“罗密欧”又有“朱丽叶”的台词。你知道吗


Tags: andintxtforiflineopenpattern
3条回答

就这么简单:

with open('play_file.txt', 'r') as play_file:
    for line in play_file:
        if 'Romeo' in line and 'Juliet' in line:
            print(line)

您的代码查找文本Romeo and Juliet,但这与Juliet and Romeo不匹配。试试if ‘Romeo’ in line and ‘Juliet’ in line。你知道吗

使用此链接下载播放文本Romeo and Juliet

# load the whole play text 
with open ('Romeo and Juliet.txt')as f:
    play_text = list(map(str.strip,f.readlines()))


#if you want the match the exact sentence or 'Romeo and Juliet' in each line 
pattern = 'Romeo and Juliet'
matching_lines = [line for line in play_text if pattern in line]
print('matching pattern' ,matching_lines)

#if you want to look for the word 'Romeo' and the word 'Juliet' in each line not nessaserly bond to each other but exist in the same line
matching_words = [line for line in play_text if 'romeo' in line.lower() and 'juliet' in line.lower()]
print('matching words' ,matching_words)

输出:

matching pattern ['Romeo and Juliet', '1.5.48 Romeo and Juliet fall in love at first sight', '3.5.1 Romeo and Juliet wake as he must leave for Mantua']
matching words ['Romeo and Juliet', 'FRIAR LAWRENCE.......Franciscan who marries ROMEO & JULIET', 'ROMEO [seeing Juliet; to a Servant 2 ] 1.5.48', "ROMEO [taking Juliet's hand] (a sonnet starts here) 1.5.104", "[Outside Juliet's balcony. ROMEO]", 'Is father, mother, Tybalt, Romeo, Juliet, is like saying', "[Juliet's bedroom, dawn. ROMEO & JULIET]", 'And Romeo dead, and Juliet, dead before,', 'Romeo, there dead, was husband to that Juliet, 5.3.240', 'Than this of Juliet and her Romeo.', '1.5.48 Romeo and Juliet fall in love at first sight', '1.5.104 
Romeo & Juliet talk and kiss, then learn they are enemies', '2.2.1 Romeo & Juliet exchange vows of love and plan to marry (balcony scene)', '2.3.1 Friar agrees to marry Romeo & Juliet', '2.6.1 Friar, Romeo & Juliet meet to be married', '3.2.41 Nurse tells Juliet Romeo killed Tybalt and is now banished', '3.3.156 They plan for Romeo to visit Juliet then flee to Mantua', '3.5.1 Romeo and Juliet wake as he must leave for Mantua', "3.5.65 Juliet's mother tries to comfort her by cursing Romeo", '5.1.1 Romeo hears Juliet is dead; he plans to die by her side', '5.3.84 Romeo finds Juliet and drinks the poison', "5.3.121 Friar arrives; Juliet wakes and sees Romeo's body; Friar flees"]

相关问题 更多 >