繁体   English   中英

在python中,如何在文本文件中搜索数字并在找到数字时打印相应的值?

[英]In python, how do I search for a number in a text file and print a corresponding value when it's found?

我有一个凸轮角度和位移的列表:

<Ignored header>
0   3
1   3
2   6
3   9
4   12
5   15
6   18
7   21
8   24
9   27
10  30
...

我将如何寻找角度并在该角度产生位移?

不必存储数据,因为在任何给定时刻我只需要两个值。

我知道这目前尚无用,但是我急切地希望了解更多有关为什么以及如何进行改进的简要说明,

camAngle = 140

camFile = open(camFileLoc)
for line in camFile:
    if line > 1:
        if camAngle in line:
        print line

非常感谢

劳伦

您基本上拥有它:

camAngle = 140

# The context manager closes the file automatically when you leave the block
with open(camFileLoc, 'r') as handle:
    next(handle)  # Skips the header

    for line in handle:
        # Splits the line on the whitespace and converts each string
        # into an integer. Then, you unpack it into the two variables (a tuple)
        angle, displacement = map(int, line.split())

        if angle == camAngle:
            print displacement
            break  # Exits the `for` loop
    else:
        # We never broke out of the loop, so the angle was never found
        print 'This angle is not in the file'

像这样:

>>> angle=5   #lets say 5 is the required angle

>>> with open("abc") as f:
    next(f)                #skip header
    for line in f:
        camangle,disp = map(int,line.split()) #convert to integers and 
                                              #store in variables

        if camangle==angle: # if it is equal to the required angle then break
            print camangle,disp
            break
...             
5 15

一种替代方案,它构建生成器并使用islice跳过不必要的标题行,并为未找到设置默认值:

from itertools import islice

with open('/path/to/your/file.txt') as fin:
    data = (map(int, line.split()) for line in islice(fin, 1, None))
    value = next( (d for a, d in data if a == 3), None) # None = default is not found

如果角度是递增的,那么您可能也可以执行基于线的方法(未经测试):

with open('/home/jon/test.txt') as fin:
    no_header = islice(fin, 1, None)
    line_no = next(islice(no_header, 0, 1), '').partition(' ')[2]

用键lelt值构建一个字典{}并设置正确的值

f = open('try.txt', 'r')
print f
dic = {}
for line in f:
    a, b = line.split()
    dic[a] = b

print dic


>>> {'10': '30', '1': '3', '0': '3', '3': '9', '2': '6', 
          '5': '15', '4': '12', '7': '21', '6': '18', '9': '27', '8': '24'}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM