[英]python: index out of range in txt file
I'm writing a script to automatically annotate a txt file. 我正在编写一个脚本来自动注释txt文件。
I open the txt file and segment it into a list of lines. 我打开txt文件并将其分割成一个行列表。 Then I iterate over every line.
然后我迭代每一行。 I want the PC to check if the previous element in the list (the line before in the text) is an empty element (the paragraph division in the text) and if it so to put an annotation.
我希望PC检查列表中的前一个元素(文本中的前一行)是否为空元素(文本中的段落除法),以及是否放置注释。
final_list = []
something = open(x, 'r', encoding='utf8', errors='ignore')
file = something.read()
y = file.split("\n")
for position, i in enumerate(y):
if position == 0:
final_list.append(i)
elif position > 0:
z = i[position-1]
if z == '':
final_list.append("<p>"+i)
return final_list
I expect to a have a final list with all the element of the previous line with some of them marked with the 我希望有一个最后一个列表,其中包含前一行的所有元素,其中一些标记为
element, but when I iterate over the list Python gives me a 元素,但是当我遍历列表时,Python给了我一个
IndexError: string index out of range
IndexError:字符串索引超出范围
I cannot understand where is the problem. 我无法理解问题出在哪里。
As you are not using values of list, instead of enumerate
take length of list and iterate. 因为你没有使用list的值,而不是
enumerate
取列表的长度和迭代。
You can try this, 你可以试试这个,
for position in range(len(y)):
if position == 0:
final_list.append(i)
elif position > 0:
z = y[position-1]
if z == '':
final_list.append("<p>"+i)
How about something like this : 这样的事情怎么样:
last_line = ''
output_lines = []
with open('file.txt', 'r') as f:
for line in f:
line = line.strip()
if last_line == '': # if last line was empty, start a new paragraph
output_lines.append('<p>')
output_lines.append(line)
elif line == '': # if current line is empty close the paragraph
output_lines.append('</p>')
else:
output_lines.append(line)
last_line = line
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.