如何使用 Python 读取文本文件中的某一行?

How to read a certain line in text file using Python?

我有一个文本文件,其中包含一个位置及其在新行上的坐标,例如

A&AB
42.289567
-83.717143
AH
42.276620
-83.739620)

我有一个遍历此列表的 for 循环,如果位置与用户输入匹配,它 returns 接下来的两行(纬度和经度)。如何使用 Python 以简洁的方式执行此操作?我知道如何在 C++ 中执行此操作,但我不知道 Python.

Python 迭代器可以手动推进,也可以隐式推进。假设你只会读取一个值,而不是一遍又一遍地检查(并且不想出于任何原因将所有值存储在内存中),你可以这样做:

def find_latlong(locname, locfile):
    with open(locfile) as f:
        for line in f:
            if line.rstrip() == locname:
                try:
                    return float(next(f)), float(next(f))
                except StopIteration:
                    break
    raise ValueError("location {!r} not found".format(locname))

这只是在提供的文件中查找与提供的名称匹配的行,并在找到时手动迭代以获取接下来的两行。

另一种假设完全是三行模式,并且不检查非名称行:

from future_builtins import map, zip  # Only on Python 2

def find_latlong(locname, locfile):
    with open(locfile) as f:
        f = map(str.rstrip, f)
        for header, lat, lng in zip(f, f, f):  # Reads three lines at a time
            if header == locname:
                return float(lat), float(lng)
    raise ValueError("location {!r} not found".format(locname))

我认为你可以做的是构建一个元组列表,其中每个元组的类型都是 (Location,Latitude,Longitude)

您可以按如下方式进行:

with open("filename","r") as f:
    lines = f.readlines()

# This is essentially splitting the lines into 
# locations, latitudes and longitudes and then merges them using zip
# to get a list of tuples
locations = zip(lines[0::3],lines[1::3], lines[2::3])

# Assuming that the userLocation contains user input
userLocation = 'foobar'

# Find the user input in our list
result = [x for x in locations if locations[0] == userLocation]

# Print the matches
for r in results:
    print "Latitude = " + str(r[1]) + "   Longitude = " + str(r[2])

查看此答案以获得一些不错的选择 单击 here。 最简单的答案是您可以使用 in 运算符或 matches = [x for x in lst if fulfills_some_condition(x)]。但是点击上面的 link 以获得更详细的答案。当然,假设您正在按照所述遍历列表。

这是同一种汤的另一种做法:

def match(name):
    with open("locat.txt") as f:
        #gr = [iter(f)]*3
        #for tag lat, lon in zip(*gr):
        for tag, lat, lon in zip(f, f, f):
            if tag.rstrip() == name:
                return float(lat.rstrip('\n)')), float(lon.rstrip('\n)'))
    return None

print(match('AY'))
print(match('xy'))

产生

(42.27, -83.73)
None

它只尝试将给定名称与每三行匹配一次,如果找不到匹配项,它 returns None

注意:没有错误检查,因此您需要确保输入数据正确(例如,如果任何条目缺少一行,即坐标值,它将不起作用。在这种情况下之一上面检查与每一行的匹配的其他答案会更好地工作并自动重新同步)。

from itertools import dropwhile
def get_data(fle, lne):
    with open(fle) as f:
        dw = dropwhile(lambda x: x.rstrip() != lne,f)
        _, a, b = next(dw,""), next(dw, "").rstrip(")\n"), next(dw,"").rstrip(")")
        return  (a,b) if b else (None, None)

lat, lon = get_data("foo.txt","A&AB")
if lat:
   # you have a match 

作为一种语言,Python强调可读性。除了使用其他人提供的迭代器的高级解决方案外,这里还有一个在文件对象上使用简单 readline 方法的解决方案:

with open(filename) as f:
    while True:
        desc =f.readline()
        lat = f.readline()
        lng = f.readline()
        if not desc:
            return None, None
        if desc.strip() == wanted:
            return float(lat), float(lng)