简体   繁体   中英

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

I have a list of cam angles and displacements:

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

How would I go about searching for an angle and producing the displacement at this angle?

It's not necessary to store the data as at any given moment I only need the two values.

I know this isn't currently working, but a brief explanation of why and how to improve would be much appreciated as I'm eager to learn more

camAngle = 140

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

Thanks very much

Lauren

You basically had it:

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'

Something like this:

>>> 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

An alternative that builds up generators and uses islice to skip an un-necessary header row, and enables setting a default value for not found:

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

If the angles are incremental, then you could perhaps do a line based approach as well (untested):

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

Build a dictionary {} with key the lelt value and value the right value

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'}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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