![](/img/trans.png)
[英]Python: how to search for specific “string” in directory name (not individual file names)
[英]how to search for a specific string in a file in python?
大家好,我是 python 新手,我想知道如何在用戶將輸入汽車名稱的鏈接中的這個 txt 文件中搜索數據,應用程序應該搜索文件並打印回這里是我的代碼我嘗試輸入 Kia Optima LX 4dr 進行搜索,但它不起作用
search = input('enter the car name you want to look for')
searchByName(search)
def searchByName(search):
outfile = open('cars.txt','r')
for line in outfile:
if search in outfile:
print(line)
break
print('no car is found with this name')
任何幫助,將不勝感激
看起來您正在處理表格數據。 在這種情況下,我建議使用 Pandas 來讀取數據、命名列並使用 Pandas 函數,而不是編寫自己的解決方案。 就像是:
import pandas as pd
df = pd.read_fwf('cars.txt', header=None)
df[df[0].str.contains('Chevrolet Impala')]
0 1 2 3 4 5 ... 13 14 15 16 17 18
50 Chevrolet Impala 4dr 0 0 0 0 0 ... 21 32 3465 111 200 73
105 Chevrolet Impala LS 4dr 0 0 0 0 0 ... 20 30 3476 111 200 73
106 Chevrolet Impala SS 4dr 0 0 0 0 0 ... 18 28 3606 111 200 73
[3 rows x 19 columns]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.