通过导入.txt文件创建列表

时间:2017-01-10 13:12:28

标签: python

我有以下代码:

myList = {"later", "test"}
aList = [];
tagCount = {}

f = ["This is a test", "Call me later"]

 for line in f:
 #Get a separate line
    fields = line.split(' ')
    for word in fields:
       if word in myList:
          print(word)

它基本上检查数组中的单词是否一个字是否对应于标记列表中的单词。它工作正常。但是我想现在用我从.txt文件获得的值替换myList列表。所以我这样做:

  with open('taglist.txt') as f:
     myList = [line.rstrip('\n') for line in f]
     myList = set(myList)

 aList = [];
 tagCount = {}

 f = ["This is a test", "Call me later"]

 for line in f:
 #Get a separate line
 fields = line.split(' ')
  for word in fields:
   if word in myList:
     print(word)

现在它似乎不起作用。我假设导入列表出了问题。对这里出了什么问题的想法?

1 个答案:

答案 0 :(得分:1)

一旦我重新缩进它,你的代码就适用于我:

with open('taglist.txt') as tl:
  myList = [line.rstrip('\n') for line in tl]
  myList = set(myList)

aList = [];
tagCount = {}

f = ["This is a test", "Call me later"]

for line in f:
#Get a separate line
  fields = line.split(' ')
  for word in fields:
    if word in myList:
      print(word)

taglist.txt

later 
test