Python-\xb字符串

Python-\xb字符串,python,Python,我是Python新手,在这段代码中,我试图编写一段代码,读取包含城市列表及其各自经度和纬度的文本文件,然后将其作为包含城市列表(包括其经度和纬度)的字典返回 文本文件如下所示: Name: Koln Latitude: 4° 45' N Longitude: 2° 55' W Name: Amersfoort Latitude: 1° 23' N Longitude: 2° 23' E import re def controller(filename): citydict = {}

我是Python新手,在这段代码中,我试图编写一段代码,读取包含城市列表及其各自经度和纬度的文本文件,然后将其作为包含城市列表(包括其经度和纬度)的字典返回

文本文件如下所示:

Name: Koln Latitude: 4° 45' N Longitude: 2° 55' W
Name: Amersfoort Latitude: 1° 23' N Longitude: 2° 23' E
import re

def controller(filename):
    citydict = {}
    filevar = open(filename, 'r')
    for line in filevar:
        city = delegate(line)
        citydict[city[0]] = city
    filevar.close()
    return citydict

def delegate(ln):
    pattern = "Name: (.*) Latitude: (.*)? (.*)' (.) Longitude: (.*)? (.*)' (.)"
    matcher = re.compile(pattern)
    match = matcher.search(ln)
    name = match.group(1)
    latitude = match.group(2), match.group(3), match.group(4)
    longitude = match.group(5), match.group(6), match.group(7)
    city = (name, latitude, longitude)
    return city

print controller('cities.txt')
我的代码是这样的:

Name: Koln Latitude: 4° 45' N Longitude: 2° 55' W
Name: Amersfoort Latitude: 1° 23' N Longitude: 2° 23' E
import re

def controller(filename):
    citydict = {}
    filevar = open(filename, 'r')
    for line in filevar:
        city = delegate(line)
        citydict[city[0]] = city
    filevar.close()
    return citydict

def delegate(ln):
    pattern = "Name: (.*) Latitude: (.*)? (.*)' (.) Longitude: (.*)? (.*)' (.)"
    matcher = re.compile(pattern)
    match = matcher.search(ln)
    name = match.group(1)
    latitude = match.group(2), match.group(3), match.group(4)
    longitude = match.group(5), match.group(6), match.group(7)
    city = (name, latitude, longitude)
    return city

print controller('cities.txt')
代码运行良好,但不知怎么的,它得到了奇怪的输出,比如2\xb。有人知道这意味着什么以及如何修复它们吗

{'Koln': ('Koln', ('4\xb0', '45', 'N'), ('2\xb0', '55', 'W')), 'Amersfoort': ('Amersfoort', ('1\xb0', '23', 'N'), ('2\xb0', '23', 'E'))}

您的正则表达式有一个错误。
表示要匹配前面的表达式,
(.*)
,零次或一次

如果度字符始终存在,则可以执行以下操作:

(.*).

它对应于unicode中的
°

>>> print u'\xb0'
°

这可能是程度特征。这只是解决问题的方法。非常感谢。