我试图获取一个包含10个句子(所有单词)的txt文件,并将其作为命令行参数传递给python脚本。我想打印包含dic
中列出的单词的句子。下面的脚本找到匹配的句子,但它会在找到匹配的单词时多次打印句子。
我可以使用另一种方法来执行此操作吗?另外,我不希望输出由一行(\ 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
答案 0 :(得分:1)
抑制输出中的重复行
在break
语句后添加print(line)
,以便字典字词上的for
循环中断
抑制换行符
额外的换行符由f.readline()
引起,因为它会在返回的字符串末尾包含\n
。您可以使用line.strip()
删除此内容,但最好使用for line in f
语法。
以下是代码:
for line in f:
words=line.split()
if len(words) > 3:
for j in words:
if j in dic:
print(line)
break
答案 1 :(得分:1)
我建议为您的单词词典创建一个set
,并为包含文件每行的单词set
创建一个&
。然后,您可以使用import sys
dic=set(["april","aprils","ask","aug","augee","august","bid","bonds","brent","buy","call","callroll","calls","chance","checking","close","collar","condor","cover"])
filename = sys.argv[1]
with open(filename) as f:
for line in f:
s = set(line.split())
if s & dic:
print(line.strip())
比较集合以获取它们的交集,或两者共有的单词。这比循环遍历列表找到类似的单词更有效。
Yes. We have paid licensed tools or free online tools.One of the best tool implemented by telerik .
http://converter.telerik.com/
http://codeconverter.sharpdevelop.net/SnippetConverter.aspx
http://www.carlosag.net/tools/codetranslator/
http://www.developerfusion.com/tools/convert/vb-to-csharp/