簡體   English   中英

在文本文件中搜索字符串時出現“ TypeError:預期字符串或類似字節的對象”錯誤-Python

[英]'TypeError: expected string or bytes-like object' error while searchin string in text file-Python

創建了一個簡單的文本文件,其內容如下:

1001
bread
20
10
1002
sugar
10
7
1003
ice
14
10

下面的Python腳本下面是用於在文本文件中搜索和查找字符串並顯示結果的。 錯誤從哪里來? 我可以對代碼進行哪些修改?

import re
with open('dbase.txt', 'r') as x:
    y=x.readlines()
    z=list(y)

    word = ['ice']
    for i in word:
        if re.search(i, z):
            print('found a match!')
        else:
            print('not found')

您正在搜索列表,但您可能想搜索一個字符串。

您不需要正則表達式。 在您的情況下,最好的解決方案可能是。

with open('dbase.txt') as file:
    words = ['ice']
    for line_number, line in enumerate(file, 1):
         split_line = line.split()  # a list of all words on that line
         for word in words:
              if word in split_line:
                  print('found "{}" on line {}'.format(word, line_number))
              else:
                  print('did not find "{}" on line {}'.format(word, line_number))

readlines()返回一個列表,因此z=list(y)是不必要的。 如果您想一次讀取一行文件,則可以在其上簡單地使用for循環:

import re
with open('dbase.txt', 'r') as x:
    word = ['ice'] # put it there to avoid redefining it for each line
    for line in x:
            for i in word:
                if re.search(i, line):
                    print('found a match!')
                else:
                    print('not found')
import re
FOUND = False
with open('dbase.txt', 'r') as x:
    for line in x.readlines():
        if line.strip() == 'ice':
            FOUND = True
            break

if FOUND:
    print("Found the ICE")
else:
    print("Couldn't find the ICE")

您看到的錯誤是由於傳遞給re.search函數的參數不正確。 它不接受數組/列表作為參數

這里查看文檔

with open(blah.txt, "rt") as f:
#your code here

全文閱讀。

暫無
暫無

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

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