Python 在文件中搜索字符串并打印文件中的相关行
我有两个文件。一个(e-number.txt)包含一个长长的物种列表和每个物种的一些信息,另一个(artsliste.txt)包含某个位置的物种。 我想在e-number.txt中提取artsliste.txt中列出的所有物种的信息。 将对应的行打印为短 我觉得我离得很近,感觉这不会太难,但我可能一开始就错了 我拥有的最新代码:Python 在文件中搜索字符串并打印文件中的相关行,python,string,file,search,Python,String,File,Search,我有两个文件。一个(e-number.txt)包含一个长长的物种列表和每个物种的一些信息,另一个(artsliste.txt)包含某个位置的物种。 我想在e-number.txt中提取artsliste.txt中列出的所有物种的信息。 将对应的行打印为短 我觉得我离得很近,感觉这不会太难,但我可能一开始就错了 我拥有的最新代码: ellenberg=open('e-number.txt').read() arter=open('artsliste.txt','r') for line in a
ellenberg=open('e-number.txt').read()
arter=open('artsliste.txt','r')
for line in arter:
art = arter.readline()
if art in ellenberg:
print(ellenberg)
artsliste.txt包含以下内容:
假悬铃木槭
扁桃槭
海马Aeculus hippocastaneum
毛冠菊
黑接骨木
坡地山羊草
山炭疽
e-number.txt包含以下内容:
新合欢树2527。8.3.6.3.0新阿卡埃纳新泽兰迪亚
Acer campestre 355577660 Acer campestre Acer campestre
扁桃槭4。5.7.7 0 0槭叶槭叶槭叶槭
假悬铃木槭5 4 6 5。6 7 6 0槭假悬铃木槭
我希望我的输出看起来像:
假悬铃木槭5 4 6 5。6 7 6 0槭假悬铃木槭
藏红花水芹1363。7.8.6.7.1番红花
红车轴草培养基2087 7 4 4 6 3 4 0红车轴草培养基
我觉得有一个功能可以打印找到的行,无论是哪种方式,我想我必须在我已有的搜索功能中设置另一个搜索功能,这没有任何意义。
希望有人能帮我找到正确的方向。
致以最诚挚的问候。来自文档:
f、 readline()从文件中读取一行;换行符
(\n)位于字符串的末尾
应该有帮助
根据您的评论更新
试试这个:
for line in arter:
art = arter.readline().strip()
index = ellenberg.find(art)
if index > -1:
line_end_index = ellenberg.find('\n', index)
print(ellenberg[index:line_end_index])
还有一个更新:
仅当行以art
开头时,此代码才会打印完整的相关行,否则它将打印从art
入口点到行末的区块
要打印整行,可以使用以下代码:
ellenberg=open('e-number.txt').readlines()
arter=open('artsliste.txt','r')
for line in arter:
for ellenberg_line in ellenberg:
line = line.strip()
if len(line) > 0 and line.strip() in ellenberg_line:
print ellenberg_line
你的文件有多大?它们能被记住吗?您能从输入文件和所需输出中显示几行吗?
对于lineno,在enumerate(filehandle)
中显示行吗?哦,是的。很抱歉枚举数为100kb。Artsliste是20kb。你应该阅读的答案。另外,您应该澄清这个问题的问题是什么-这不是一个代码编写服务。谢谢,这部分很有效。问题是这一行应该来自另一个文件。这是一个飞跃。我将其编辑为打印(ellenberg[index-22:line_end_index]),以获得整行内容,这不是最好的方式,但它目前仍然有效。稍后将继续。谢谢。它让我知道了物种名称前面的数字,尽管它并不漂亮。
ellenberg=open('e-number.txt').readlines()
arter=open('artsliste.txt','r')
for line in arter:
for ellenberg_line in ellenberg:
line = line.strip()
if len(line) > 0 and line.strip() in ellenberg_line:
print ellenberg_line