#!/usr/bin/env python
import sys, re
def find_position(line):
pun = ""
if re.search(r"[.?!]+", line):
pun = re.search(r"[.?!]+", line).group()
pos = line.find(pun)
pos = pos+len(pun)-1
return pos
def sentence_splitter(filename):
f = open(filename, "r")
for line in f:
line = line.strip()
print line + "\n"
while line:
pos = find_position(line)
line2 = line[ : pos+1].split(" ")
length = len(line2)
last_word = line2[length -1]
try:
if re.search(r"[A-Z]+.*", last_word) or line[pos+1] != " " or line[pos+2].islower() :
print line[:pos+1],
line = line[pos+1:]
else:
print line[ : pos+1]
line = line[pos+1 :]
except :
print " error here!!"
f.close()
return " bye bye"
if __name__=="__main__":
print sentence_splitter(sys.argv[1])
执行它
python sentence_splitter6.py README | more
发生错误
KeyboardInterrupt
close failed in file object destructor:
sys.excepthook is missing
lost sys.stderr
我也要按clr + c
它没有被它自己关闭
尝试了这方面的东西 How to handle a file destructor throwing an exception?
How to silence "sys.excepthook is missing" error?
链接也不满意请帮助
答案 0 :(得分:0)
首先,你的问题在这里:
while line:
pos = find_position(line)
line2 = line[:pos + 1].split(" ")
length = len(line2)
last_word = line2[length - 1]
line
未被修改,因此如果它真实一次,它始终为真,则while
无法结束。
然后,KeyboardInterrupt
并非来自您的执行,而是来自您按C-c
,暂停您的计划。
您还应该在编写python代码时尊重PEP8,也可以使用flakes8
和/或pylint
进行检查。
这是符合PEP8的版本(仍有无限循环):
#!/usr/bin/env python3
import sys, re
def find_position(line):
pun = ""
if re.search(r"[.?!]+", line):
pun = re.search(r"[.?!]+", line).group()
pos = line.find(pun)
pos = pos+len(pun)-1
return pos
def sentence_splitter(filename):
with open(filename, "r") as infile:
for line in infile:
line = line.strip()
print(line + "\n")
while line:
pos = find_position(line)
line2 = line[:pos + 1].split(" ")
length = len(line2)
last_word = line2[length - 1]
if ((re.search(r"[A-Z]+.*", last_word) or
line[pos+1] != " " or
line[pos+2].islower())):
print(line[:pos+1], end='')
line = line[pos+1:]
else:
print(line[:pos + 1])
line = line[pos + 1:]
return " bye bye"
if __name__ == "__main__":
print(sentence_splitter(sys.argv[1]))
最后,您应该评论您的代码,以便包括您在内的所有人都能理解您正在做的事情,例如:
def find_position(line):
"""Finds the position of a pun in the line.
"""
同样find_pun_position
可能是一个更好的名字......