我现有的工作代码是:
#!/usr/bin/env python3
import glob
import xml.etree.ElementTree as ET
filenames = glob.glob("C:\\Users\\####\\Desktop\\BNC\\[000-ZZZ]*.xml")
out_lines = []
for filename in filenames:
with open(filename, 'r', encoding="utf-8") as content:
tree = ET.parse(content)
root = tree.getroot()
for w in root.iter('w'):
if w.text is None:
w.text = "####"
lemma = w.get('hw')
if lemma is None:
lemma = "####"
pos = w.get('pos')
if pos is None:
pos = "####"
tag = w.get('c5')
if tag is None:
tag = "####"
out_lines.append(w.text + "\t" + lemma + "\t" + pos + "\t" + tag)
with open("C:\\Users\\####\\Desktop\\bnc.txt", "w", encoding="utf-8") as out_file:
for line in out_lines:
out_file.write("{}\n".format(line))
有 4,049 个 xml 源文件,这会产生超过 2GB 的输出,其中的行数比我可以轻松导入其他包进行操作的要多得多。
我手动分批处理了 100 个文件,但这仍然导致一些输出文件超过 1,048,576 行
我想让打印循环在每 1,048,576 行(或更少,能够指定将是理想的)之后基于设置的文件名递归地输出文件。
例如
- bnc-001.txt 1,048,576 行
- bnc-002.txt 1,048,576 行
- ...
- bnc-050.txt 56,789 行(摘自空中)
不知道如何开始这个。