2017-01-10 149 views
-1

创建列表,我有以下代码:通过导入.txt文件

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

'[line.rstrip( '\ n')在f.readlines线( )]' – MMF

+0

@MMF'.readlines'是不必要的。 @Frits Verstraten究竟“似乎没有工作”? – laike9m

+1

我希望你没有那个缩进,因为它是不正确的 –

回答

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 
+0

是的,但你在第9行后面声明f。 f = [“这是一个测试”,“稍后给我打电话”]。当评论出来时它是否也有效? –

+0

对不起,当f注释失败时 – CoderMike

+0

这是正确的 - 你通过重新使用f而使代码混淆,但它确实起作用 – CoderMike