简体   繁体   English

如何在python 3中搜索文本文件

[英]how to search a text file in python 3

I have this text file that has lists in it.我有这个包含列表的文本文件。 How would I search for that individual list?我将如何搜索该个人列表? I have tried using loops to find it, but every time it gives me an error since I don't know what to search for.我曾尝试使用循环来查找它,但每次它都会给我一个错误,因为我不知道要搜索什么。 I tried using a if statement to find it but it returns -1.我尝试使用 if 语句来查找它,但它返回 -1。 thanks for the help谢谢您的帮助

I was doing research on this last night.我昨晚正在研究这个。 You can use pandas for this.您可以为此使用熊猫。 See here: Load data from txt with pandas .请参见此处: 使用 pandas 从 txt 加载数据 One of the answers talks about list in text files.答案之一是关于文本文件中的列表。

You can use:您可以使用:

   data = pd.read_csv('output_list.txt', sep=" ", header=None)

   data.columns = ["Name", "b", "c", "etc."]

Add sep=" " in your code, leaving a blank space between the quotes.在代码中添加 sep=" ",在引号之间留一个空格。 So pandas can detect spaces between values and sort in columns.因此,pandas 可以检测值之间的空格并按列进行排序。 Data columns isenter code here for naming your columns.数据列是在此处输入用于命名列的代码。

With a JSON or XML format, text files become more searchable.使用 JSON 或 XML 格式,文本文件变得更易于搜索。 In my research I've decided to go with an XML approach.在我的研究中,我决定采用 XML 方法。 Here is the link to a blog that explains how do use Python with XML: http://www.austintaylor.io/lxml/python/pandas/xml/dataframe/2016/07/08/convert-xml-to-pandas-dataframe .以下是解释如何将 Python 与 XML 结合使用的博客链接: http : //www.austintaylor.io/lxml/python/pandas/xml/dataframe/2016/07/08/convert-xml-to-pandas-数据框

If you want to search the data frame try:如果要搜索数据框,请尝试:

import pandas as pd

txt_file = 'C:\path\to\your\txtfile.txt'

df = pd.read_table(txt_file, sep = ",")

row = df.loc[df['Name'] == 'bob']

Print(row)

Now depending how your text file is formated, your results will not work for every text file.现在取决于您的文本文件的格式,您的结果不适用于每个文本文件。 The idea of a dataframe in pandas helps u create a CSV file formats. Pandas 中数据框的想法可以帮助您创建 CSV 文件格式。 This giving the process a repeatable structure to enable testing results.这为过程提供了可重复的结构,以实现测试结果。 Again I recommend using a JSON or XML format before implementing pandas data frames in ur solution.我再次建议在您的解决方案中实施 Pandas 数据框之前使用 JSON 或 XML 格式。 U can then create a consistent result, that is testable too!然后你可以创建一个一致的结果,这也是可测试的!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM