尝试使用Python 3仅拉回大文件中的外来脚本

问题描述 投票:0回答:1

我有一个非常大的文件,其中混合了英语和外语材料(主要是阿拉伯文字和一些其他语言)。我不关心检测或识别语言。我是 Python 新手,正在努力编写这段代码。我希望我的代码能够读取 .txt 文件,忽略英语/拉丁语/ascii 可编码字符中的任何内容,然后仅将外语材料打印到新的 .txt 文件中。

到目前为止,我已经:

sourceDoc = open("test_doc.txt", 'r')
destDoc = open("test_doc_dest.txt", 'w')
for line in sourceDoc:
    try:
        line.isascii()
    except:
        destDoc.write(line)
sourceDoc.close()
destDoc.close()

我知道我的代码可能有问题,我要求它查找外语材料并将整行写入新文件。我真的只想将外语材料写入新文件,并丢弃该行的其余部分(如果它是英语/拉丁字符)。

我不断获得代码中第 3 行和源文档中第 23 行的回溯,这是外语材料的第一个实例出现的地方。

python python-3.x arabic file-writing
1个回答
0
投票

我倾向于使用匹配非拉丁字符的正则表达式模式(这还包括脚本值为

Common
Inherited
的字符,即保留标点符号和空格。

要使用 Unicode POSIX 或 Perl 样式表示法,我需要使用 regex 模块而不是 re 模块。

安装模块:

pip install -U regex

reregex都有一个方法

re.fullmatch
regex.fullmatch
,仅当整个字符串与模式匹配时才返回匹配项。

下面的代码可以用不同的方式编写,要点是1)使用regex模块代替或re; 2) 使用

\P{Latin}
匹配非拉丁文本。

re.fullmatch(r'\P{Latin}+', line)
re.match(r'^\P{Latin}+$', line)
都合适。其他一切都是流动的,并且可以编写适合您的代码。

import regex as re
pattern = re.compile(r'\P{Latin}+')
with open("multi-lang.txt", "r", encoding="utf-8") as f:
    lines = (line.rstrip() for line in f)
    lines_subset = [line for line in lines if bool(re.fullmatch(pattern, line))]
with open("multi-lang-out.txt", "w", encoding="utf-8") as o:
    o.write('\n'.join(lines_subset))
© www.soinside.com 2019 - 2024. All rights reserved.