[英]python search in text file
我想在txt文件中搜索變量“ elementid”
f = open("wawi.txt", "r")
r = f.read()
f.close()
for line in r:
if elementid in line:
print("elementid exists")
break
elementid可能是123456
txt包含三行:
1235
56875
123456
但是代碼沒有打印“ elementid存在”,為什么? 我使用python 3.4
當您read
文件時,會將整個內容讀取為一個字符串。
當您對其進行迭代時,一次只能得到一個字符。
嘗試打印行:
for line in r:
print line
你會得到
1
2
3
5
5
6
8
7
5
1
2
3
4
5
6
您需要說:
for line in r.split('\n'):
...
只是重新排列您的代碼
f = open("wawi.txt", "r")
for line in f:
if elementid in line: #put str(elementid) if your input is of type `int`
print("elementid exists")
break
將整數轉換為字符串,然后遍歷文件中的各行,檢查當前行是否與elementid
匹配。
elementid = 123456 # given
searchTerm = str(elementid)
with open('wawi.txt', 'r') as f:
for index, line in enumerate(f, start=1):
if searchTerm in line:
print('elementid exists on line #{}'.format(index))
elementid exists on line #3
一種更可靠的解決方案是從每行中提取所有數字,然后在所述數字中找到數字。 如果數字在當前行中的任何地方存在,則將聲明匹配。
numbers = re.findall(r'\d+', line) # extract all numbers
numbers = [int(x) for x in numbers] # map the numbers to int
found = elementid in numbers # check if exists
import re
elementid = 123456 # given
with open('wawi.txt', 'r') as f:
for index, line in enumerate(f, start=1):
if elementid in [int(x) for x in re.findall(r'\d+', line)]:
print('elementid exists on line #{}'.format(index))
f = open("wawi.txt", "r")
for lines in f:
if "elementid" in lines:
print "Elementid found!"
else:
print "No results!"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.