0

I'm opening a file that might be something like this...

It was the best of times,

it was the worst of times.

Let's say this file name is myFile1.txt

I want the file to split up into this

[['It','was','the','best','of','times',','],
 ['it','was', 'the','worst','of','times','.']]

It should be a list of strings...

This is my idea...

def Split():
  inFile=open('myFile1.txt','r')

  for line in inFile:
    separate=list(line.split())
    return(separate)

print(Split())

would something like this work?

4

3 回答 3

0
def Split():
    results=[]
    inFile=open('myFile1.txt','r')
    for line in inFile.readlines():
        results.append(line.split())
    return results

print(Split())

然后一切都应该正常工作。:)

于 2013-07-16T03:49:23.003 回答
0

仅通过一次 for 循环后,您将返回。

你想要的是一个生成器,使用yield而不是return:

yield separate

现在您的函数创建了一个可以迭代的生成器对象。

for line in split():
    print line

(此外,最好不要将您的函数命名为与内置方法相同的名称。它们可能不会发生冲突,但比抱歉更安全。)

于 2013-07-16T03:51:06.777 回答
0

您可以通过separate = []在循环外部声明,然后将结果附加line.split()到列表来获得所需的列表。您不需要使用该list函数,因为它line.split()已经返回了一个列表。

你可以试试这个:

def Split():
  separate = []
  with open('myFile1.txt','r') as inFile:
    for line in inFile:
      separate.append(line.split())
  return(separate)
于 2013-07-16T03:52:30.750 回答