有关python的一些问题(文件) [英] Some questions on python (files)

查看:227
本文介绍了有关python的一些问题(文件)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新来的,我也有新的Python。我希望得到您的帮助,谢谢。

I'm new here and I'm also new to python. I would like to get your help, please.

def lines(path, prefix):
  funf = open(path, 'r')
  dictionary = {}
  for lines in funf:
     word = lines.split()
     a_word = (word[0])
     dictionary[a_word] = dictionary.get(a_word, 0) + 1
  if prefix != word[0]:
     return 0
  else:
     return dictionary[prefix]
  funf.close()

当我运行此:

    inpath = "filetext1.txt"
    print(lines(inpath,"But"))

和我得到这样的:

 Traceback (most recent call last):
 File "C:...\...\....py", line 29, in <module>
 print(lines(inpath,"This"))
 File "C:...\...\....py", line 11, 
 in lines
if prefix != word[0]:
UnboundLocalError: local variable 'word' referenced before assignment

这是什么问题,我如何改变它,它会更好? 我问的想法和选项(但是请,不改变更多的事情,在code ......它必须是这样的结构!

What is the problem, how can I change it so it would be better? I'm asking for ideas and options (but please, without changing more things in the code... It has to be something like this structure!!!

谢谢!

推荐答案

在你的code时,如果preFIX!=字[0] 部分正在发生的之外的循环后,循环运行完毕。因此,对于一个非空文件,将是文件的最后一行的分裂。而对于一个空文件,将永远不会被置位,产生正是您发布的错误。

In your code, the if prefix != words[0] part is happening outside the loop, after the loop has finished running. So, for a non-empty file, words will be the split of the last line of the file. And for an empty file, words will never have been set, causing exactly the error you posted.

作为一个方面说明,即对于F中的行:是循环对一些全局对象 F ,而不是文件刚刚打开,这就是所谓的 funf 。所以,我怀疑 F 是某种空可迭代的,和你看到的这个功能,即使该文件,你想看看IS的不是空。如果你要循环 funf ,你必须告诉Python的 funf ,不是 F

As a side note, that for lines in f: is looping over some global object f, not the file you just opened, which is called funf. So, I suspect that f is some kind of empty iterable, and you're seeing this function even when the file you wanted to look at is not empty. If you want to loop over funf, you have to tell Python funf, not f.

和你已经知道这是不正确的,因为在此评论:

And you already know this isn't correct, as in this comment:

字线的分裂。我不能在外面做的for循环

word is the split of line. I can't do it outside the for loop

循环,则需要缩进以匹配循环中的code。在Python中,块结构是基于缩进级别:

If you want to run it inside the loop, you will need to indent it to match the code inside the loop. In Python, block structure is based on indentation level:

def lines(path, prefix):
    funf = open(path, 'r')
    dictionary = {}
    for lines in f:
        word = lines.split()
        a_word = (word[0])
        dictionary[a_word] = dictionary.get(a_word, 0) + 1
        if prefix != word[0]:
            return 0
        else:
            return dictionary[prefix]
    funf.close()

这意味着你将不再得到一个错误; 将永远在使用它来定义。

That means you'll no longer get an error; words will always be defined when you use it.

的问题与此code:你是返回 ING每一行后,这意味着你永远也没有机会第二线;你返回 ING在关闭前的文件,这意味着永远不会被关闭的文件;这是非常误导用于个别事物和奇异的变量名的东西列出多个变量的名字;这是混淆使用本地变量具有相同名称的功能;等等。但有一件事的时间...

There are other problems with this code: you're returning after each line, meaning you'll never get to the second line; you're returning before you close the file, meaning the file never gets closed; it's very misleading to use plural variables names for individual things and singular variable names for lists of things; it's confusing to use a local variable with the same name as the function; etc. But one thing at a time…

的拔牙半个多小时后,你终于解释你想做什么:

After half an hour of pulling teeth, you finally explained what you're trying to do:

我试图计算行数的第一个字相匹配的preFIX

I'm trying to count the number of lines whose first word matches the prefix

有没有办法做到这一点这种结构。无论你做了如果内环路或缩小,这没有任何意义。

There is no way to do that with this structure. Whether you do the if inside the loop or out, it doesn't make any sense.

要解决这个问题最简单的方法是删除如果完全。你建立的每个第一个字计数的字典,对吗?所以,仅仅查找值对于给定的preFIX底:

The simplest way to fix it is to remove the if entirely. You're building up a dictionary of counts of each first word, right? So, just look up the value for the given prefix at the end:

def lines(path, prefix):
    funf = open(path, 'r')
    dictionary = {}
    for lines in funf:
        word = lines.split()
        a_word = (word[0])
        dictionary[a_word] = dictionary.get(a_word, 0) + 1
    funf.close()
    return dictionary.get(prefix, 0)

这会工作,但它是令人难以置信的浪费,建立这整个字典只是为了得到一个值出来,并让您的code复杂得多,以及...整个事情可以写成:

This will work, but it's incredibly wasteful to build up this whole dictionary just to get a single value out of it, and makes your code much more complicated as well… the whole thing could be written as:

def lines(path, prefix):
    with open(path) as f:
        return sum(1 for line in f if line.startswith(prefix))

下面是我的filetext1.txt:

Here's my filetext1.txt:

This is a test.
But this isn't.
But this is.
And this isn't.

输出显然应2,对吧?

The output should obviously be 2, right?

和我的code-的简单的解决办法的这两个版本的双内胆,两个打印UT:

And both versions of my code—the "simplest fix" and the two-liner—both print ut this:

2

这工作在这两个的Python 3.3和2.7。如果它不为你工作,或者你没有在复制和粘贴code或输入文件没有开始任何行,但

This works in both Python 3.3 and 2.7. If it's not working for you, either you failed at copying and pasting the code, or your input file doesn't have any lines starting with "But ".

这篇关于有关python的一些问题(文件)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆