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