打印仅包含第二个元素的列表



我正在计算拆分语句的长度,但当试图打印出包含[1]的行/列表时,总是会出现索引超出范围的错误。

代码:

for line in open("testing.txt"):
strip = line.rstrip()
words = strip.split(';')
first = words[0]
for test in words:
if words[1] in words:
print(words)
else:
continue

示例.txt文件的分割输出例如为:

['"What does Bessie say I have done?" I asked.']
['Be seated somewhere', ' and until you can speak pleasantly, remain silent."']
['Of farthest Thule', ' and the Atlantic surge']
['Pours in among the stormy Hebrides."']
['"Alright, let's get out of here!" I yelled.']

所以有些句子只有[0]元素,而那些有[1]元素的句子是我试图打印出来的句子(当前的if/else语句不起作用(。

预期输出(基本上是任何有第二个元素的拆分语句/列表(:

['Be seated somewhere', ' and until you can speak pleasantly, remain silent."']
['Of farthest Thule', ' and the Atlantic surge']

您之所以出现此错误,是因为您试图访问仅包含1个字符串的数组的第二个元素。在这种情况下,您需要检查阵列的长度

for line in open("testing.txt"):
strip = line.rstrip()
words = strip.split(';')
for test in words:
if len(words) > 1:
print(words)
else: # this else is not necessary
continue

编辑:如果要打印每个句子中至少包含一个";"只有一次,您实际上不必使用for循环。获得所需输出的一种简洁方法是:

for line in open("testing.txt"):
strip = line.rstrip()
words = strip.split(';')
if len(words) > 1:
print(words)

据我所知,您只是试图打印包含多个元素的单词列表。

一个简单的方法是:

for line in open("testing.txt"):
strip = line.rstrip()
words = strip.split(';')
# first = words[0]
for test in words:
if len(words) > 1:
print(words)

在这里,你只是检查单词的长度是否大于1,如果是,则打印

编辑:我认为for循环是不必要的。您只需要打印长度大于1的单词列表。因此:

for line in open("testing.txt"):
strip = line.rstrip()
words = strip.split(';')
if len(words) > 1:
print(words)

这里你只是在;上拆分句子,然后在拆分后检查列表(命名单词(的长度是否大于1;如果是,则打印命名单词列表。

编辑2:正如S3DEV所指出的,您正在为关键字打开一个内部文件,一旦您退出for循环,它就不会自动关闭您的文件。因此,文件指针一直处于打开状态,直到程序完全停止,这可能会导致奇怪的问题。最佳实践是使用with关键字。with关键字会自动打开文件,并在块执行完成后将其关闭,这样您就不会遇到任何奇怪的问题。保持文件指针打开的窗体。

with open("testing.txt", "r") as f: # this line open file as f in read-only format
for line in f:
strip = line.rstrip()
words = strip.split(';')
if len(words) > 1:
print(words)

最新更新