[英]python search in text file
i want to search for a variable "elementid" in a txt 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
the elementid is maybe 123456 elementid可能是123456
the txt contains three lines: txt包含三行:
1235
56875
123456
but the code does not print "elementid exists", why ? 但是代码没有打印“ elementid存在”,为什么? I work with python 3.4
我使用python 3.4
When you read
the file you read the whole thing into a string. 当您
read
文件时,会将整个内容读取为一个字符串。
When you iterate over it you get one character at a time. 当您对其进行迭代时,一次只能得到一个字符。
Try printing the lines: 尝试打印行:
for line in r:
print line
And you'll get 你会得到
1
2
3
5
5
6
8
7
5
1
2
3
4
5
6
You need to say: 您需要说:
for line in r.split('\n'):
...
Just rearranging your code 只是重新排列您的代码
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
Convert the integer to a string THEN iterate over the lines in the file, checking if the current line matches the elementid
. 将整数转换为字符串,然后遍历文件中的各行,检查当前行是否与
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
A more robust solution is to extract all numbers out of each line and find the number in said numbers. 一种更可靠的解决方案是从每行中提取所有数字,然后在所述数字中找到数字。 This will declare a match if the number exists anywhere in the current line.
如果数字在当前行中的任何地方存在,则将声明匹配。
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.