【发布时间】:2017-06-24 05:52:16
【问题描述】:
我正在呼吁 Stack Overflow 的集体智慧,因为我正在竭尽全力试图弄清楚如何做到这一点,而且我是一名自学成才的新手。
我有一个 txt 文件的 Letters to the Editor,我需要将其拆分成各自的文件。
所有文件都以相对相同的方式格式化:
For once, before offering such generous but the unasked for advice, put yourselves in...
Who has Israel to talk to? The cowardly Jordanian monarch? Egypt, a country rocked...
Why is it that The Times does not urge totalitarian Arab slates and terrorist...
PAUL STONEHILL Los Angeles
There you go again. Your editorial again makes groundless criticisms of the Israeli...
On Dec. 7 you called proportional representation “bizarre," despite its use in the...
Proportional representation distorts Israeli politics? Huh? If Israel changes the...
MATTHEW SHUGART Laguna Beach
Was Mayor Tom Bradley’s veto of the expansion of the Westside Pavilion a political...
Although the mayor did not support Proposition U (the slow-growth initiative) his...
If West Los Angeles is any indication of the no-growth policy, where do we go from here?
MARJORIE L. SCHWARTZ Los Angeles
我认为解决此问题的最佳方法是尝试使用正则表达式来识别以全部大写字母开头的行,因为这是真正分辨一个字母在哪里结束而另一个字母在哪里开始的唯一方法。
我尝试了很多不同的方法,但似乎没有一种方法能完全正确。我看到的所有其他答案都是基于可重复的行或单词。 (例如这里发布的答案how to split single txt file into multiple txt files by Python 和这里Python read through file until match, read until next pattern)。当我必须调整它以接受所有大写单词的正则表达式时,这一切似乎都不起作用。
我设法得到的最接近的是下面的代码。它创建正确数量的文件。但是在创建第二个文件之后,一切都出错了。第三个文件是空的,其余的文本都是乱序和/或不完整的。应该在文件 4 中的段落在文件 5 或文件 7 等中或完全丢失。
import re
thefile = raw_input('Filename to split: ')
name_occur = []
full_file = []
pattern = re.compile("^[A-Z]{4,}")
with open (thefile, 'rt') as in_file:
for line in in_file:
full_file.append(line)
if pattern.search(line):
name_occur.append(line)
totalFiles = len(name_occur)
letters = 1
thefile = re.sub("(.txt)","",thefile)
while letters <= totalFiles:
f1 = open(thefile + '-' + str(letters) + ".txt", "a")
doIHaveToCopyTheLine = False
ignoreLines = False
for line in full_file:
if not ignoreLines:
f1.write(line)
full_file.remove(line)
if pattern.search(line):
doIHaveToCopyTheLine = True
ignoreLines = True
letters += 1
f1.close()
我愿意完全放弃这种方法并以另一种方式(但仍使用 Python)。任何帮助或建议将不胜感激。请假设我是一个没有经验的新手,如果你足够出色,愿意花时间帮助我。
【问题讨论】:
-
我建议将程序拆分为更小的函数,例如:“将文件行读入列表”、“检查行是否应该开始一个新文件”、“将行列表拆分为列表列表”行,每个列表都是新文件的内容”,“将行列表写入文件”。实际上,第一个和最后一个函数已经在 Python 中实现(
readlines和writelines方法)。 -
Good reading about debugging。说,我真的不明白你的
while/for循环的逻辑到底是什么:他们的invariants 是什么,例如在每个周期的每次迭代之前应该保持哪些条件?更多注意事项:doIHaveToCopyTheLine变量根本不用,ignoreLines变量可以用break语句替换。 -
@yeputons 关于您的第一条评论:这就是我开始时认为应该做的,但我不知道该怎么做。至于你的第二条评论,我也不确定我的循环在做什么......我正在拼凑代码,遇到一个新问题并试图让它工作。所以你的困惑也是我的困惑。