【问题标题】:can't access different text files in python无法在python中访问不同的文本文件
【发布时间】:2012-08-04 09:43:46
【问题描述】:
def input_files(file):
    s=0
    #word=raw_input('enter the word you want to search\n')
    file=file.readlines()
    for lines in file:
        if word in lines:
            s+=lines.count(word)
    print s
word=raw_input('enter the word you want to search\n')
file =open("2.txt")
file2=open("3.txt")
input_files(file)
input_files(file2)

这是我正在做的代码,现在我得到了我想要的结果,但现在我想让我的代码成熟。我不想一次又一次地调用方法来读取文本文件,例如如果我有 39 个数据集文本文件,所以我必须调用函数 39 TIMES 这已经足够了,所以如果有人知道我不必一次又一次调用该方法的方式,它只会自动获取文本文件并显示他们的输出,并根据哪个文件有更多单词的结果对它们进行排名。

【问题讨论】:

  • 我认为这是不可能通过循环实现的。
  • 删除file=file.readlines。文件是 Python 中行的迭代器

标签: python file-io file-handling


【解决方案1】:

你可以用循环来做:

导入系统

def input_files(fd, word):
    """return the occurences of `word` in a file"""
    s = 0
    for lines in fd:
        if word in lines:
            s += lines.count(word)
    return s


if __name__ == '__main__':
    word = raw_input('Enter the word you want to search: ')
    total = 0

    for filename in sys.argv[1:]:
        try:
            print("Searching for %s in %s..." % (word, filename))
            with open(filename, "r") as fd:
                found = input_files(fd, word)
                total += found
                print("\t... found %i occurence(s)\n" % found)
        except IOError:
            print("\t... cannot open %s !" % filename)

    print("\nTotal: %i occurences" % total)

它将处理所有作为参数传递给脚本的文件...


说明:

sys.argv 是包含通过命令行传递给脚本的参数的变量。

例如,如果您执行命令python my_script.py foo bar,则my_script.py 中的sys.argv 变量将包含["my_script.py", "foo", "bar"]

如您所见,sys.argv 的第一个元素是脚本本身的名称,所以我们必须跳过它(sys.argv[1:] 表示 «sys.argv 从索引 1 开始的所有项目 »,第 0 项被跳过)。

所以在上面的脚本中,所有作为参数传递给脚本的文件都会被处理。 当然,如果其中一个文件不存在,它就会失败。

来源

【讨论】:

  • 你能告诉我关于 sys.argy[1:] 我不知道它有什么想法
  • 但这不是打开我的文件!没有输出
  • 它正在打开您作为参数传递的文件,我刚刚测试过。但是你到底想做什么呢?
  • 可能在代码中加了raw_input(),这样就可以匹配原代码了;在此期间,可能包括所有代码,而不仅仅是 for 循环
  • import re import sys def input_files(file): s=0 #word=raw_input('输入你要搜索的单词\n') #file=file.readlines() for line in file : if word in lines: s+=lines.count(word) print s word=raw_input('输入要搜索的单词\n') #file =open("2.txt") """file2=open( "3.txt") input_files(file) input_files(file2)""" for file in sys.argv[1:]: with open(file,"r") as fd: input_files("2.txt","3 .txt")
【解决方案2】:

您的代码略有错误,因为它将子词计为词的出现次数。例如 "This is a bad test".count('a') 将给出 2 而不是 1。

正确的分词有点棘手,但这里有一个简单的开始,在标点符号或空格处分词。

def input_files(f, word):
    print sum(re.split('[ .,;:"]').count(word) for line in f)

一个不错的选择是使用正则表达式来查找单词的出现(尽管我认为这会使事情变得更加困难)。

与您的版本相比,此代码还有一些其他改进:如果您使用文件对象作为迭代器,则无需显式执行 readlines() 即可获得行(这避免了将整个文件读入 RAM 并将其表示为列表),当你说 if word in line: s += line.count(word) 时,你实际上比你只写 s += line.count(word) 更慢,因为它需要对行进行 2 次扫描,而不仅仅是一次。

我还将您正在扫描的单词传递给函数,因为它使代码更明显(您甚至可以为此版本编写单元测试)。

要继续...而不是将字数打印出来,您可能想要返回它(因为您想找到字数最多的文件)。然后您可以计算每个文件中给定单词的出现次数,并对它们进行排序。

这是一个解决方案,它使用命令行参数并且没有任何错误检查。 用法:[程序] word file1 file2...

import sys

def words_in_file(filename, word):
    with open(filename, 'r') as f:
        return sum(re.split('[ .,;:"]', line).count(word) for line in f)

def files_by_wordcount(filenames, word):
    counts = [(words_in_file(filename, word), filename) for filename in filenames]
    return sorted(counts, reverse=True)

if __name__ == '__main__':
    for count, filename in files_by_wordcount(sys.argv[2:], sys.argv[1]):
        print filename, count

【讨论】:

  • +1 :我没有注意到代码在计算子词:-)
  • 感谢您的建议,但我是 python 新手,如何创建文件对象作为最后一个答案还要求我使用文件对象作为参数
  • 我只专注于 UNI gram ,到目前为止我对 bi gram 没有任何顾虑
  • @munieb 你可以通过调用open函数来创建一个文件对象:docs.python.org/library/stdtypes.html#file-objects
  • 你的分词行不行。 line.split(' .,;:"') 不会在传递的任何字符上拆分,它会在传递的 string 上拆分,该字符串(希望!)不存在于字符串中。
【解决方案3】:

您需要阅读 sys.argv http://docs.python.org/library/sys.html 的此文档,它可以帮助您理解此库,并且通过此库您可以访问目录中的不同文本文件。 sys.argv[1:] [1:] 是参数,最好不要从零开始。 http://www.ibiblio.org/g2swap/byteofpython/read/sys-module.html 这更清晰更好,也专注于你的编码

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-19
    • 2020-12-07
    • 1970-01-01
    • 1970-01-01
    • 2016-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多