首先,我最近开始学习python。所以我是初学者。
1111 1 3
1112 1 2
1113 2 3
1114 1 7
1115 7 2
假设我在文本文件中有这些值。与标题中一样,我想在特定列中搜索txt文件中的特定值,然后返回特定值的行,但搜索的"值"除外。
示例:
在第一列搜索1113
值
然后将2 3
返回为:
x = 2
y = 3
答案 0 :(得分:0)
你可以试试这个:
<div class="rates">
<? foreach ($rates as $rate) { ?>
<div class="rates-block" <? if ($rate->id % 4 != 1) { ?> style="margin-left: 48px;" <? } ?>>
<img src="/images/aukc_image/<?= $rate->img ?>" class="products-img rate-img" alt="product-1">
</div>
<input class="rate-radio" type="radio" name="radio1" value="<?= $rate->count ?>;<?= $rate->price ?>">
<? } ?>
</div>
答案 1 :(得分:0)
尝试这样的事情:
with open('file.txt', 'r') as f:
for line in f:
if line.startswith('1113'):
line = line.split()
x = int(line[1])
y = int(line[2])
作为'file.txt'
放置您的文件名,而'1113'
放置您要查找的值。祝你好运
答案 2 :(得分:0)
有一个csv模块可以为您完成所有肮脏的工作:
import csv
def find(filename, number):
with open(filename) as file:
reader = csv.DictReader(file,
fieldnames=['col1', 'col2', 'col3'],
delimiter=' ')
for line in reader:
if line['col1'] == str(number):
return (line['col2'], line['col3'])
if __name__ == '__main__':
(x, y) = find('data.txt', 1113) or (None, None)
print(x, y)
答案 3 :(得分:0)
我更喜欢:
search_text = '1113'
with open(FileName) as f:
for i in f:
if i.strip() != '':
for j in i.strip().split():
if j[0] == search_text:
x = int(i[1])
y = int(i[2])
答案 4 :(得分:0)
这将允许您搜索任何列上的任何值。
import csv
def find(reader, col, val):
for row in reader:
if row[col] == val:
return row
raise ValueError('Value {} not found in row {}'.format(val, col))
def findexcept(reader, col, val):
r = find(reader, col, val)
r.pop(col)
return r
with open('searchdata.txt') as f:
lines = (line.strip() for line in f)
c = csv.reader(lines, delimiter=' ', skipinitialspace=True)
try:
x = findexcept(c, 0, '1114')
print(x)
except ValueError as ve:
print('Error: {}'.format(ve))