![](/img/trans.png)
[英]How to read a file line by line, then print the line if it contains a string with a range of value in Python?
[英]Read line in file, print line if it contains string
我有一個工作代碼,可以打開一個文件,查找一個字符串,並在包含該字符串的情況下打印該行。 我這樣做是為了可以手動決定是否應從數據集中刪除該行。
但是,如果我可以告訴程序讀取包含兩個逗號之間的字符串的行部分,那就更好了。
我現在擁有的代碼(見下文)
with open("dvd.txt") as f:
for num, line in enumerate(f, 1):
if " arnold " in line:
num = str(num)
print line + '' + num
像這樣打印每一行:
77.224998664,2014-10-19,386.5889,the best arnold ***** ,81,dvd-action,Cheese 5gr,online-dvd-king93,0.19976,18,/media/removable/backup/2014-10-19/all_items/cheese-5gr?feedback_page=1.html, ships from: Germany ships to: Worldwide ,2014-07-30,online-dvd-king,93 1
我希望它打印出來:
,the best arnold ***** , 1
要么
the best arnold ***** 1
我讀了這個問題,但我希望避免使用CSV。
如果由於某種原因而難以在逗號或其他任何特定字符之間查找文本,則在要查找的字符串前后打印這3個字會很有用。
使用str.split()
非常簡單。 如下修改函數將產生所需的輸出。
with open("dvd.csv") as f:
for num, line in enumerate(f, 1):
if " arnold " in line:
num = str(num)
print line.split(',')[3] + '' + num
str.split
通過指定的分隔符將字符串分成列表。 要訪問所需的列表條目,只需提供適當的索引(在您的情況下為3)。
str.format()
,您可以使用str.format()
方法產生輸出,以使其更加str.format()
:
print "{} {}".format(line.split(',')[3], num)
這也使您可以刪除num = str(num)
因為format方法可以處理多種數據類型(與不能進行字符串連接的情況相反)。
或者,您可以使用如下正則表達式:
with open("dvd.txt") as f:
for num, line in enumerate(f, 1):
re_arnold = re.search(r',\s*([^,]*?arnold[^,]*?)\s*,', line)
if re_arnold:
print '{} {}'.format(re_arnold.group(1), num)
然后,這將提取整個條目(逗號之間),而不管其位於哪個字段中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.