Python - 字符串中的 xb

标签 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 = {}
    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'))}

最佳答案

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

(.*)?

如果度数字符始终存在,您可以这样做:

(.*).

关于Python - 字符串中的 xb,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46526966/

相关文章:

Python3进度条和gzip下载

python - Pygame错误: self. spritedict [spr] = surface_blit(spr.image, spr.rect)

python - 在 `python` 上运行 R 代码,语法错误 : keyword can't be an expression error Message

python - 如何跟踪进程的资源使用情况?

python - 参数列表的长度 (3) 和 CL 生成的参数数量 (9) 不一致

导入库时 Python StanfordNLP 包错误

python - 如何将元素从另一个列表添加到列表?

python - 如何在二进制张量中找到相邻真值组?

python - 在 Sklearn 异常值检测方法中将 'contamination' 参数设置为 'auto' 有什么作用?

python - py2neo graph.merge() 的行为与 Cypher MERGE 不同?