Python字符串编码和==

jme*_*etz 1 python string utf-8

我在使用python中的字符串时遇到了一些问题,而==我认为它们应该是这样,而且我认为它与编码方式有关.基本上,我解析了存储在zip存档中的一些以逗号分隔的值(特别是GTFS提要,对于那些好奇的人).

我在python中使用ZipFile模块打开zip存档的某些文件,然后将其中的文本与一些已知值进行比较.这是一个示例文件:

agency_id,agency_name,agency_url,agency_phone,agency_timezone,agency_lang
ARLC,Arlington Transit,http://www.arlingtontransit.com,703-228-7433,America/New_York,en
Run Code Online (Sandbox Code Playgroud)

我正在使用的代码是尝试在文本的第一行中识别字符串"agency_id"的位置,以便我可以在任何后续行中使用相应的值.这是代码的片段:

zipped_feed = ZipFile(feed_name, "r")
agency_file = zipped_feed.open("agency.txt", "r")

line_num = 0
agencyline = agency_file.readline()
while agencyline:
    if line_num == 0:
        # this is the header, all we care about is the agency_id
        lineparts = agencyline.split(",")
        position = -1
        counter = 0
        for part in lineparts:
            part = part.strip()
            if part == "agency_id":
                position = counter              
        counter += 1
        line_num += 1
        agencyline = agency_file.readline()
    else:
        .....
Run Code Online (Sandbox Code Playgroud)

此代码适用于某些zip存档,但不适用于其他zip存档.我做了一些研究,并尝试打印repr(部分),我得到'\ xef\xbb\xbfagency_id'而不是'agency_id'.有谁知道这里发生了什么以及我如何解决它?感谢您的帮助!

Kji*_*jir 5

这是一个字节顺序标记,它告诉文件的编码,在UTF-16和UTF-32的情况下,它也告诉文件的字节顺序.您可以解释它或检查它并从字符串中删除它.要删除它,你可以这样做:

import codecs

unicode(part, "utf8").lstrip(codecs.BOM_UTF8.decode("utf8", "strict"))
Run Code Online (Sandbox Code Playgroud)