我在Python 3.8.0中工作,我想删除以小写字母开头的字符串,它仅在那些字符串为空且无法删除的空字符串时才起作用。我试着剥离它,并且它可以工作,但是不能用于空字符串。 我的下面的代码
gezegdes_file = open(gezegdes_betekenis, 'r')
content = gezegdes_file.readlines()
gezegdes_file.close()
gezegdes_opgeschoond = open('gezegdes_opgeschoond.txt', 'w')
for rule in content:
rule = rule.replace(rule.lower(), ' ').strip()
# rule = "".join([s for s in rule.strip().splitlines(True) if s.strip("\r\n")])
rule = rule.replace('ij', 'y')
# rule = rule.replace('\n\n','\n').replace('\n\n','\n')
rule = rule.replace('.', '').replace('!', '').replace('?', '').upper()
print(rule)
gezegdes_opgeschoond.write(str(rule) + '\n')
gezegdes_opgeschoond.close()
我尝试用空字符串替换rule.lower,并且可以,但是我无法删除空字符串。 下面的代码结果
AAN DE RAND VAN HET RAVYN BLOEIEN DE MOOISTE BLOEMEN
AAN DE VEREN KENT MEN DE VOGEL
AAN DE VRUCHTEN KENT MEN DE BOOM
AAP WAT HEB JE MOOIE JONGEN
ACHTER DE WOLKEN SCHYNT DE ZON
AL DOENDE LEERT MEN
AL IS DE LEUGEN NOG ZO SNEL, DE WAARHEID ACHTERHAALT HAAR WEL
ALLE GEKHEID OP EEN STOKJE
ALLE HENS AAN DEK
ALLE HOUT IS GEEN TIMMERHOUT
ALLE WEGEN LEIDEN NAAR ROME
ALS APEN HOGER KLIMMEN WILLEN, ZIET MEN GAUW HUN BLOTE BILLEN
最后两个句子之间有一条白线,并且在最后两行之间有一个以小写字母开头的字符串,所有以小写字母开头的字符串都需要删除。 该文件很长,并且文件中有几个空行,因为我必须删除以小写字母开头的字符串。 删除最后两个句子之间的白线的解决方案是什么?
答案 0 :(得分:0)
一种方法是简单地跳过空行开头,因此您可以像这样缩短循环:
gezegdes_file = open(gezegdes_betekenis, 'r')
content = gezegdes_file.readlines()
gezegdes_file.close()
gezegdes_opgeschoond = open('gezegdes_opgeschoond.txt', 'w')
for rule in content:
if not rule: # if it's an empty string, skip everything
continue
rule = rule.replace(rule.lower(), ' ').strip()
# rule = "".join([s for s in rule.strip().splitlines(True) if s.strip("\r\n")])
rule = rule.replace('ij', 'y')
# rule = rule.replace('\n\n','\n').replace('\n\n','\n')
rule = rule.replace('.', '').replace('!', '').replace('?', '').upper()
print(rule)
gezegdes_opgeschoond.write(str(rule) + '\n')
gezegdes_opgeschoond.close()
如果您的测试行与rule == ''
略有不同,则可以调整测试行,但这应该可以给您一个思路。
编辑
正如@khelwood所表明的那样,在所有这些替换运行之后,可能会出现一个空行,因此在末尾移动if
语句检查会更安全(或另外)。我选择向下移动。在这种情况下,如果rule
不为空,我们将打印并写入。
gezegdes_file = open(gezegdes_betekenis, 'r')
content = gezegdes_file.readlines()
gezegdes_file.close()
gezegdes_opgeschoond = open('gezegdes_opgeschoond.txt', 'w')
for rule in content:
rule = rule.replace(rule.lower(), ' ').strip()
# rule = "".join([s for s in rule.strip().splitlines(True) if s.strip("\r\n")])
rule = rule.replace('ij', 'y')
# rule = rule.replace('\n\n','\n').replace('\n\n','\n')
rule = rule.replace('.', '').replace('!', '').replace('?', '').upper()
if rule: # if it's not an empty string, then print/write
print(rule)
gezegdes_opgeschoond.write(str(rule) + '\n')
gezegdes_opgeschoond.close()