簡體   English   中英

在 Python 中檢查文件中是否有多個匹配項

[英]Check if there are multiple matches in a file in Python

用戶輸入數據。 通過文件的所有行檢查數據。 如果他輸入的內容對應於一行,則打印出來。

如果結果不止一個,我想循環輸入過程,直到用戶足夠細化他的選擇,以便只找到一個結果。 我可以在“ mutipleAnswersAreFound ”處使用什么?

我的代碼:

def search()
    with open("file.txt") as f:
        nameSearch = str(raw_input("Enter first name, last name, email, or phone: "))
        for line in f: 
            if nameSearch in line: 
                print line
            else if 'mutipleAnswersAreFound' :
                search()

line.count(nameSearch)將返回nameSearch在字符串line出現的次數。 如果此計數大於 1,那么您就有了elif案例。

例如

"aaa".count("aa")將返回 2 因為我們有兩次出現字符串 "aa"

你的代碼看起來像

cnt = line.count(nameSearch)
if cnt == 1:
    print line
elif cnt > 1:
    search()

如果您希望事件由空格分隔,那么您可以執行此操作

words = line.split()
cnt = 0
for word in words:
    if nameSearch == word: cnt += 1
    if cnt > 1: break
if cnt == 1:
     print line
elif cnt > 1:
     search()

將其包裹在一個無限循環中,當匹配計數小於或等於 1 時中斷它。

def search()
  while True:
    count=0
    with open("file.txt") as f:
      nameSearch = str(raw_input("Enter first name, last name, email, or phone: "))
      for line in f: 
        if nameSearch in line: 
            print line
            count+=1
      if count > 1 :
        print 'Multiple matches, please refine your search'
      else: 
        break

我認為你可以使用正則表達式,在 python 中導入 re。 例如:

import re
expression = re.compile('(wordto)')
example = ' hi worldto, how are wordto xD wordto'
matches = expression.findall(example)
if matches:
    print matches
    print 'the count is', len(matches)

>>>['wordto', 'wordto']
>>>the count is 2

暫無
暫無

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

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