import re
sum=0
file = open("pro.txt").readlines()
for lines in file:
word= len(re.findall('(^|[^\w\-])able#1(?=([^\w\-]|$))', lines))
if word>0:
sum=sum+1
pro.txt
0 6 9 able#1
0 11 34 unable#1
9 12 22 able#1
0 6 9 able#1-able#1
0 11 34 unable#1*able#1
我希望得到单词的值,就像用户输入句子并且它包含单词而不是像9 6 0
或0 6 9
一样检索它的值,但现在作为样本我只是想要,如果我只关注这个txt文件中唯一能够#1的单词,我怎样才能通过它检索值,因为我只是试图分裂它而不仅仅是将队列放在上面
for lines in file:
k=lines.split()
print k
['0', '6', '9', 'able#1', 'you#1']
['0', '11', '34', 'unable#1']
['9', '12', '22', 'able#1']
['0', '6', '9', 'able#1-able#1']
['0', '11', '34', 'unable#1*able#1']
['9', '12', '22', 'able#1_able#1']
预期产出:
enter the word you want to find in text file : able#1
word found !!
values are
0 6 9
答案 0 :(得分:0)
for line in file:
print line.split()[:3]
您将获得每行的前三个元素,例如['0','6','9']。
如果您想逐个查找3个数字,可以先用文件内容构建一个字典。
counts_by_word = dict((line[3], line[:3]) for line in file)
print counts_by_word["able#1"]
# Output: ['9', '12', '22']
答案 1 :(得分:0)
你走了:
s = "able#1"
for line in open("pro.txt").readlines():
if s == line.split()[3].strip():
print line.rsplit(' ',1)[0].strip()
<强>输出强>
>>>
0 6 9
9 12 22
如果您需要在数字之间只留一个空格,请使用:
print ' '.join(line.split()[:3])
<强>更新强>
完整代码:
s = raw_input("enter the word you want to find in text file : ")
f = False
for line in open("pro.txt").readlines():
if s == line.split()[3].strip():
if not f:
print "word found !!"
f = True
print ' '.join(line.split()[:3])
<强>输出强>
>>>
enter the word you want to find in text file : able#1
word found !!
0 6 9
9 12 22
>>>