首页 > 解决方案 > 如何检查txt文件的内容

问题描述

我正在尝试创建一个 python 脚本,该脚本将从文本文件中读取数据,然后检查它是否具有 .(两个字母),这很好地告诉我是否是国家代码。我尝试过使用 split 和其他方法,但没有得到它的工作?这是我到目前为止的代码->

# Python program to
# demonstrate reading files
# using for loop
import re

file2 = open('contry.txt', 'w')
file3 = open('noncountry.txt', 'w')
# Opening file
file1 = open('myfile.txt', 'r')
count = 0
noncountrycount = 0
countrycounter = 0
# Using for loop
print("Using for loop")
for line in file1:
    count += 1
    
    pattern = re.compile(r'^\.\w{2}\s')
    if pattern.match(line):
        print(line)
        countrycounter += 1
    else:
        print("fail", line)

        noncountrycount += 1

print(noncountrycount)
print(countrycounter)
file1.close()
file2.close()
file3.close()

txt文件里面有这个

.aaa    generic American Automobile Association, Inc.
.aarp   generic AARP
.abarth generic Fiat Chrysler Automobiles N.V.
.abb    generic ABB Ltd
.abbott generic Abbott Laboratories, Inc.
.abbvie generic AbbVie Inc.
.abc    generic Disney Enterprises, Inc.
.able   generic Able Inc.
.abogado    generic Minds + Machines Group Limited
.abudhabi   generic Abu Dhabi Systems and Information Centre
.ac country-code    Internet Computer Bureau Limited
.academy    generic Binky Moon, LLC
.accenture  generic Accenture plc
.accountant generic dot Accountant Limited
.accountants    generic Binky Moon, LLC
.aco    generic ACO Severin Ahlmann GmbH & Co. KG
.active generic Not assigned
.actor  generic United TLD Holdco Ltd.
.ad country-code    Andorra Telecom
.adac   generic Allgemeiner Deutscher Automobil-Club e.V. (ADAC)
.ads    generic Charleston Road Registry Inc.
.adult  generic ICM Registry AD LLC
.ae country-code    Telecommunication Regulatory Authority (TRA)
.aeg    generic Aktiebolaget Electrolux
.aero   sponsored   Societe Internationale de Telecommunications Aeronautique (SITA INC USA)

我现在收到此错误文件“C:/Users/tyler/Desktop/Python Class/findcountrycodes/Test.py”,第 15 行,在 file1 中的行:文件“C:\Users\tyler\AppData\Local\Programs \Python\Python36\lib\encodings\cp1252.py",第 23 行,解码返回 codecs.charmap_decode(input,self.errors,decoding_table)[0] UnicodeDecodeError: 'charmap' codec can't decode byte 0x90 in position 8032 : 字符映射到

标签: python

解决方案


这通常不仅仅是代码的问题,所以我们需要所有的上下文来重现、调试和解决。

编码错误

最后的提示是您粘贴的控制台输出(错误、堆栈跟踪)。

阅读堆栈跟踪和研究

这就是我阅读和分析错误输出(Python 的堆栈跟踪)的方式:

... C:/用户/tyler/桌面 ...

... findcountrycodes/ Test.py ",第 15 行...

... Python36 \lib\encodings* cp1252 *.py ...

... UnicodeDecodeError:“charmap”编解码器无法解码位置 8032 中的字节 0x90:

从这个输出中,我们可以提取重要的上下文信息来研究和解决问题:

  1. 您正在使用Windows
  2. 脚本中的第 15 行Test.py指向读取文件的错误语句:file1 = open('myfile.txt', 'r')
  3. 您正在使用Python 3.6,当前使用的编码是Windows 1252 ( cp-1252 )
  4. 根本原因是,读取文件时UnicodeDecodeError经常出现的Python Exception

你现在可以:

  • 针对这个例外研究UnicodeDecodeErrorStackoverflow 和网络: .
  • 通过添加此上下文来改进您的问题(作为关键字、标签或转储为纯输出)

尝试不同的编码

一个答案建议使用当今常见的UTF-8open(filename, encoding="utf8")

检测文件编码

一种有条理的解决方法是:

  1. 检查文件的编码或字符集,例如使用编辑器,在 Windows记事本Notepad++
  2. 使用正确的 Python 代码打开文件encoding

也可以看看:

国家代码过滤行

因此,您只需要带有country-codes 的行。

过滤预期

然后期望过滤输入文件的这3 行

.ad country-code    Andorra Telecom
.ac country-code    Internet Computer Bureau Limited
.ae country-code    Telecommunication Regulatory Authority (TRA)

使用正则表达式的解决方案

正如你已经做的那样,测试文件的每一行。测试该行是否以这 4 个字符开头.xx xx可以是任何 ASCII 字母)。

正则表达式解释

此正则表达式测试有效的两个字母的国家/地区代码:

^\.\w{2}\s
  • ^从字符串的开头( line)
  • \.(第一)字母应该是一个
  • \w{2}(后跟)任意两个单词字符(⚠️也匹配_0
  • \s(后跟)单个空格(空白、制表符等)

Python代码

这是在您的代码中完成的,如下所示(假设line从读取行填充):

import re

line = '.ad '
pattern = re.compile(r'^\.\w{2}\s')
if pattern.match(line):
    print('found country-code')

这是IDEone 上的可运​​行演示

进一步阅读


推荐阅读