比较并打印python中的大写字符串

Compare and print Uppercase string in python

我需要比较我的grepoutput.txt和mylist中的单词,并打印出那些常见的,但得到的个别字母作为输出,没有任何比较。请帮助。谢谢您。

1
2
3
4
5
6
7
8
9
10
MyList = ['WORD1', 'WORD2', 'WORD3']

file = open('/home/~/grepoutput.txt','r')
data = file.read()
file.close()

for line in data:
    for content in line.split():
        if content in MyList:
            print content

grepoutput.txt包含:你好世界

单词1单词2单词3单词4

我也试过用集合逻辑,但没用

1
2
setoutput = set(MyList) & set(content)
    print setoutput

下面是输出:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
[]
searching now...
W
set(['W'])
O
set(['O'])
R
set(['R'])
D
set(['D'])
1
set(['1'])


set(['
'
])
W
set(['W'])
O
set(['O'])
R
set(['R'])
D
set(['D'])
2
set(['2'])


set(['
'
])
W
set(['W'])
O
set(['O'])
R
set(['R'])
D
set(['D'])
3
set(['3'])


set(['
'
])
H
set(['H'])
e
set(['e'])
l
set(['l'])
l
set(['l'])
o
set(['o'])


set(['
'
])


我想你在找file.readlines()file.read()将创建单个字符串,因此您将遍历该字符串的每个字符。file.readlines()将创建一个字符串列表,其中每个字符串都是文件的一部分,用换行符分隔。医生帮助解释这一点。


1
2
3
4
5
6
7
8
9
10
11
12
import re

MyList = ['WORD1', 'WORD2', 'WORD3']

file = open('/home/chi/Desktop/hello/grepoutput.txt','r')
data = file.readlines() #THIS
file.close()

for line in data:
    for content in line.split():
        if content in MyList:
            print content