如何将文本文件中的单词与另一个单词进行比较?

如何将文本文件中的单词与另一个单词进行比较?
with open("file.txt") as f:
     for line in f:
         for word in f:
             if word == 'President':
                print('a')

即使我在文本文件中出现 4 次“总统”一词,也不会打印任何内容。我怎样才能让它检查

我的文本文件如下所示:

President Kacey Genicke

President Alexandra Twomey

President Aldous Graddell

President Bernie Jenicek

Officer Cyrill Vernazza

Officer Sutton Spier

Officer Isabella Seer

Officer Abbey Holdforth

Faculty Officer Lennie Lomaz

Faculty Officer Brant Howle

Faculty Officer Dionysus Summerbell

Faculty Officer Calhoun Duguid

Faculty Officer Tremain Arnaez

Faculty Officer Mirabella Trathan

Faculty Officer Dex Darcy

我希望我的输出看起来像这样:

   Kacey Genicke

   Alexandra Twomey

   Aldous Graddell

   Bernie Jenicek

我尝试这样做:

with open("file.txt") as f:
    for line in f:
            if 'President' in line:
                print(line[10])

这是每位总统的第一封信。

答案1

内循环的for word in f:作用是不是迭代“字”在一行中,但与for line in f消耗文件行相同f

要检查'President'单词是否包含在一行中,您需要做的是:

with open("file.txt") as f:
     for line in f:
         if 'President' in line:
             print('a')

要仅打印以President消除了前缀的单词开头的行:

with open("file.txt") as f:
     for line in f:
         if line.startswith('President'):
             print(line.replace('President', '').strip())

答案2

首先,我认为这是你的缩进。您可以尝试以下操作:

with open('file.txt') as f:
    count = 0 
    for line in f:
        columns = line.split() 
        if len(columns) > 1 and 'President' in line:  
            print(columns[1], columns[2])
            count += 1
    print("There are ", count, "Presidents found")

President如果在该特定行中找到,这应该打印整行。然后我们将行分成列并相应地打印列

然而,对于这种情况,使用awk可能比 python 更合适。

awk '/President/{c++; print $2,$3 } END { printf("There were %d Presidents found\n", c)}' file.txt 
  • 寻找总统
  • 增加计数器 C.
  • 打印第二列和第三列
  • 结尾。打印找到的总出现次数。

相关内容