【问题标题】:How do I search for text within a tab delimited file and print this information?如何在制表符分隔的文件中搜索文本并打印此信息?
【发布时间】:2015-07-11 16:14:28
【问题描述】:

我需要在制表符分隔的文本文件中搜索某些内容。用户应该输入文件和需要搜索的东西。然后程序应该返回用户输入的单词所在的整行。到目前为止,我有两个模型,因为我一直从不同的角度来解决这个问题。第一个程序如下:

import csv

searchfile = raw_input ('Which file do you want to search?   ')
try:
    input_file = open (searchfile, 'rU')
except:
    print "Invalid file. Please enter a correct file"

csv_file_object = csv.reader(open(searchfile, 'rb')) 
header = csv_file_object.next()   

data=[]                          
for row in csv_file_object:      
    data.append(row)             

searchA = raw_input ('which author?')

author_search = data[0::,0] == searchA

if author_search in searchfile:
    print author_search

第一个程序的问题是弹出这个错误:

TypeError:列表索引必须是整数,而不是元组

因此我尝试了这种方法:

import csv

searchfile = raw_input ('Which file do you want to search?   ')
try:
    input_file = open (searchfile, 'rU')
except:
    print "Invalid file. Please enter a correct file"


with open(searchfile) as f:
    reader = csv.reader(f, delimiter="\t")
    d = list(reader)

searchtype = raw_input ('Search on author or journal/conference or [Q = quit]')


if searchtype == 'author':
    searchdataA = raw_input ("Input author name")
    if searchdataA in input_file:
        print line

elif searchtype == 'journal' or 'conference' or 'journal/conference':
    searchdataJ = raw_input ("input journal/conference name")
    if searchdataJ in d:
        print line

elif searchtype == 'Q':
    print "Program left"

else:
    print "please choose either author or journal/conference"

这无法超越输入搜索参数。

如果我完全走错了轨道,那么任何关于如何使用这两个程序的帮助都将非常感激,那么指向有用材料的链接会很棒。

【问题讨论】:

  • 您能提供几行您要搜索的文件吗?

标签: python list python-2.7 csv search


【解决方案1】:

为什么不简单

fname = raw_input("Enter Filename")
author = raw_input("Enter Author Name:")
if author in open(fname,"rb").read():
   print "match found"

如果你想看看你可以做的线条

print re.findall(".*%s.*"%(author),open(fname,"rb").read())

正如人们指出的那样,这样做是更好的形式

with open(fname,"rb") as f:
     data = print re.findall(".*%s.*"%(author),f.read())

虽然在 CPython 中它会立即被垃圾收集,所以这不是一个真正的问题......

【讨论】:

  • 我喜欢你的简单回答,但在这两种情况下你都没有关闭文件描述符。
  • 不在 CPython 中(OP 运行的可能性为 99.9%)......但你的权利,我想这是一个坏习惯......我从来没有听说过任何问题让读取句柄保持打开状态如果他们没有 GC(在 CPython 中他们会马上)
  • 我同意它通常不是问题,但是 SO 是一个被大量新程序员访问的教育资源,所以我认为我们应该强烈强调良好的编码实践,例如清理您使用的资源,即使有技术原因我们可以不这样做。此外,读取期间引发的异常肯定会导致解释器在不清理其文件描述符的情况下退出。
  • @skrrgwasme .... 这会留下一个打开的文件描述符...不会破坏文件完整性...并且会留下一个不可恢复的内存字节(直到下次重新启动).. . 不管怎样,我补充说他们可能应该使用良好的编码实践
【解决方案2】:

我认为你让这变得比它需要的更复杂了。由于您要打印目标单词出现的整行,因此您实际上并不需要 CSV 模块。您没有进行任何复杂的解析。

searchfile = raw_input ('Which file do you want to search?   ')
searchA = raw_input ('which author?')

with open(searchfile) as infile:
    for line in infile:
        if searchA in line:
            print('  '.join(line.split()))
            break # remove this if you want to print all matches instead of
                  # just the first one

请注意,在打印行时,我首先拆分行(默认情况下在空格上拆分),然后重新加入字段,它们之间有两个空格。我认为这样做对您来说是一个好方法,因为您正在控制台上打印制表符分隔的字段。减少多余的空间将使您的打印件更易于阅读,但使用两个空格仍然可以轻松区分各列。

您可以通过提示用户任何搜索词来概括它,而不是指定“作者”。这可能是要走的路,因为您的第二个代码 sn-p 建议您可能要搜索其他字段,例如“期刊”或“会议”:

target_term = raw_input("Which term or phrase would you like to find?")

由于此方法搜索并打印整行,因此无需处理单独的列和不同类型的搜索词。它只是一次查看整行并打印匹配的行。

【讨论】:

  • 看起来你打字比我快,我们发布了相同的答案。除了break,因为我预计可能不止一条匹配线
【解决方案3】:

由于您并没有真正使用不同的搜索方法,这取决于您是在搜索作者、期刊、会议还是期刊/会议。因此,您实际上可以在线进行全文搜索。因此,明智的做法是在处理文件之前从用户收集您需要的所有数据,这样您就可以只输出匹配的行。如果用户传递一个相当大的 CSV 文件,那么你的方式会占用太多的内存。

with open(searchfile, 'r') as f:
    for line in f:
        if line.find(searchA) > -1:
            print line

这样您可以尽可能快地循环文件并打印出所有匹配的行。

.find() 函数将索引返回到他在字符串中找到匹配项的位置,如果未找到该字符串,则返回 -1。因此,您可以根据值“估计”匹配的位置,但如果您真的想区分作者、期刊等,那么您将不得不拆分行。在我的示例中,我假设作者字段是 CSV 行中的第六个字段:

with open(searchfile, 'r') as f:
    for line in f:
        fields = line.split("\t")
        if len(fields) > 5:                    # check length of fields array
            if fields[5].find(searchA) > -1:   # search straight in author field
                print line                     # return full line

【讨论】:

  • line.find 在找到 0..N 的情况下返回索引,如果不是,则返回 -1 if -1 将评估为 True
【解决方案4】:

我想到的第一件事就是:

def check_file(file_name, author_name):
    with open(file_name) as f:
        content = f.readlines()
    for line in content:
        if author_name in line:
            print "Found: ", line

希望对你有用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-14
    • 2018-01-04
    • 1970-01-01
    相关资源
    最近更新 更多