![](/img/trans.png)
[英]Trying to search case insensitive keywords from a log text (.txt) file
[英]Trying to save keywords from a .txt file to an array and use that array to search another doc for the keywords
我想保存在一个文件名为keywordtest.txt包含诸如一堆关键字的networkmanager
, filemanager
和speaker
等(每个在.txt文件自己的线)。
我已经将它保存到数组中,但是我希望它使用存储在数组中的单词在另一个名为test的文档中进行搜索,并调出找到关键词的整个行并将该行存储在另一个文档中称为results.txt。
我设法使它使用数组中的单词进行搜索并将它们保存到另一个文件,但是仅在行中不包含某些内容的情况下才会找到它:
例如,我搜索networkmanager
,如果它只是文件中我自己搜索的一行上的networkmanager
,它将找到它,但是如果它像“我是一个networkmanager”一样,它将不会选择它。
#!\usr\bin\python
x = []
with open("keywordtest.txt","r") as y:
for line in y:
x.append(line)
print x
theFile = open ("results.txt", "w")
searchfile = open("test", "r")
for line in searchfile:
for word in x:
if word in line:
theFile.write(line)
theFile.close()
searchfile.close()
编辑:我发布的代码是我尝试的一种版本,我在网上看到有人在某些地方使用“单词”而不是“行”并尝试了它,但它不喜欢它,下面的代码是我拥有的代码开始工作,但仅显示我要搜索的单词,如果它们自己显示。
#!\usr\bin\python
x = []
with open("keywordtest.txt","r") as y:
for line in y:
x.append(line)
print x
theFile = open ("results.txt", "w")
searchfile = open("test", "r")
for line in searchfile:
if line in x: theFile.write(line)
if line in x: print line
theFile.close()
searchfile.close()
#!\usr\bin\python
x = []
with open("keywordtest.txt","r") as y:
for line in y:
x.append(line)
print x
theFile = open ("results.txt", "w")
searchfile = open("test.txt", "r")
for line in searchfile:
for word in x:
if word in line.strip():
theFile.write(word)
theFile.close()
searchfile.close()
根据您的修改:
#!\usr\bin\python
x = []
with open("keywordtest.txt","r") as y:
for line in y:
x.append(line)
print x
theFile = open ("results.txt", "w")
searchfile = open("test.txt", "r")
for line in searchfile:
for item in x:
if item in line:
theFile.write(line)
print line
theFile.close()
searchfile.close()
这会将匹配的单词保存在theFile.txt中,并假设关键字test.txt每行与test.txt相同仅包含一个单词,将打印出匹配项
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.