我想要一個包含10個句子(全部單詞)的txt文件,並將其作爲命令行參數傳遞給python腳本。我想打印包含dic
中列出的單詞的句子。下面的腳本找到匹配的句子,但是它找到匹配的單詞時會多次打印這些句子。Python:我需要打印返回唯一的句子
有沒有其他的方法可以用來做到這一點?另外,我不想輸出到由線分離(\ n)的
import sys
dic=["april","aprils","ask","aug","augee","august","bid","bonds","brent","buy","call","callroll","calls","chance","checking","close","collar","condor","cover"]
f=open(sys.argv[1])
for i in range(0,10):
line=f.readline()
words=line.split()
if len(words) > 3:
for j in words:
if j in dic:
print(line)
輸出:
eighty two is what i am bidding on the brent
eighty two is what i am bidding on the brent
eighty two is what i am bidding on the brent
call on sixty five to sixty seventy
call on sixty five to sixty seventy
call on sixty five to sixty seventy
call on sixty five to sixty seventy
call on sixty five to sixty seventy
no nothing is going on double
i am bidding on the option for eighty five
i am bidding on the option for eighty five
recross sell seller selling sept
recross sell seller selling sept
recross sell seller selling sept
recross sell seller selling sept
recross sell seller selling sept
blah blah blah blah close
所需的輸出:
eighty two is what i am bidding on the brent
call on sixty five to sixty seventy
no nothing is going on double
i am bidding on the option for eighty five
recross sell seller selling sept
blah blah blah blah close
在'print(line)'後面放一個'break',所以它不檢查其他單詞。 – trincot
@trincot,謝謝你解決了80%的問題。使用休息完全滑脫了我的想法。 –
另外20%是由'line'字符串中的換行符引起的。看到我的答案。 – trincot