Python,检查数据文件中的某些行

发布于 2024-10-15 17:27:37 字数 655 浏览 5 评论 0原文

我从来没有上过使用 python 的课程,只上过 c、c++、c#、java 等。 这应该很容易,但我感觉我错过了 python 反应的一些巨大的东西。 我所做的就是读取文件,检查仅包含数字的行,计算类似的行数并显示它。

所以我打开、读取、条带化、检查 isdigit() 并递增。怎么了?

# variables
sum = 0
switch = "run"

print( "Reading data.txt and counting..." )

# open the file
file = open( 'data.txt', 'r' )

# run through file, stripping lines and checking for numerics, incrementing sum when neeeded
while ( switch == "run" ):
    line = file.readline()
    line = line.strip()

    if ( line.isdigit() ):
        sum += 1

    if ( line == "" ):
        print( "End of file\ndata.txt contains %s lines of digits" %(sum) )
        switch = "stop"

I've never taken a class that used python, just c, c++, c#, java, etc..
This should be easy but I'm feeling like I'm missing something huge that python reacts to.
All I'm doing is reading in a file, checking for lines that are only digits, counting how many lines like that and displaying it.

So I'm opening, reading, striping, checking isdigit(), and incrementing. What's wrong?

# variables
sum = 0
switch = "run"

print( "Reading data.txt and counting..." )

# open the file
file = open( 'data.txt', 'r' )

# run through file, stripping lines and checking for numerics, incrementing sum when neeeded
while ( switch == "run" ):
    line = file.readline()
    line = line.strip()

    if ( line.isdigit() ):
        sum += 1

    if ( line == "" ):
        print( "End of file\ndata.txt contains %s lines of digits" %(sum) )
        switch = "stop"

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

她比我温柔 2024-10-22 17:27:37

在 Python 中判断是否已到达文件末尾的正确方法是而不是查看它是否返回空行。

相反,迭代文件中的所有行,当到达文件末尾时循环将结束。

num_digits = 0
with open("data.txt") as f:
    for line in f:
        if line.strip().isdigit():
            num_digits += 1

因为文件可以迭代,所以您可以使用生成器表达式来简化它:

with open("data.txt") as f:
   num_digits = sum( 1 for line in f if line.strip().isdigit() )

我还建议不要使用保留的 Python 关键字(例如 sum)作为变量名,而且使用字符串比较进行流程也是非常低效的就像你正在做的逻辑。

The correct way in Python to tell if you've reached the end of a file is not to see if it returns an empty line.

Instead, iterate over all the lines in the file, and the loop will end when the end of the file is reached.

num_digits = 0
with open("data.txt") as f:
    for line in f:
        if line.strip().isdigit():
            num_digits += 1

Because files can be iterated over, you can simplify this using a generator expression:

with open("data.txt") as f:
   num_digits = sum( 1 for line in f if line.strip().isdigit() )

I would also recommend against using reserved Python keywords such as sum as variable names, and it's also terribly inefficient to use string comparisons for flow logic like you're doing.

淡淡の花香 2024-10-22 17:27:37
sum=0
f=open("file")
for line in f:
    if line.strip().isdigit():
         sum+=1
f.close()  
sum=0
f=open("file")
for line in f:
    if line.strip().isdigit():
         sum+=1
f.close()  
上课铃就是安魂曲 2024-10-22 17:27:37

我刚刚尝试运行你的代码:

matti@konata:~/tmp$ cat data.txt 
1
a
542
dfd
b
42
matti@konata:~/tmp$ python johnredyns.py 
Reading data.txt and counting...
End of file
data.txt contains 3 lines of digits

它在这里工作正常。你的data.txt里有什么?

I just tried running your code:

matti@konata:~/tmp$ cat data.txt 
1
a
542
dfd
b
42
matti@konata:~/tmp$ python johnredyns.py 
Reading data.txt and counting...
End of file
data.txt contains 3 lines of digits

It works fine here. What's in your data.txt?

淡水深流 2024-10-22 17:27:37

正如几个人所说,您的代码似乎运行完美。也许您的“data.txt”文件位于与当前工作目录不同的目录中(不一定是脚本所在的目录)?

然而,这里有一种更“Pythonic”的方式来做同样的事情:

counter = 0
with open('data.txt', 'r') as infile:
    for line in infile:
        if line.strip().isdigit():
            counter += 1
print 'There are a total of {0} lines that start with digits'.format(counter)

你甚至可以将它变成一个单行:

counter = sum([line.strip().isdigit() for line in open('data.txt', 'r')])

不过我一开始会避免这条路线......它的可读性要差得多!

As several people have said, your code appears to work perfectly. Perhaps your "data.txt" file is in a different directory than your current working directory (not necessarily the directory that your script is in)?

However, here's a more "pythonic" way of doing the same thing:

counter = 0
with open('data.txt', 'r') as infile:
    for line in infile:
        if line.strip().isdigit():
            counter += 1
print 'There are a total of {0} lines that start with digits'.format(counter)

You could even make it a one-liner with:

counter = sum([line.strip().isdigit() for line in open('data.txt', 'r')])

I'd avoid that route at first though... It's much less readable!

烧了回忆取暖 2024-10-22 17:27:37

你如何运行该程序?您确定 data.txt 有数据吗?文件中是否有空行?

试试这个:

while 1:
    line = file.readline()
    if not line: break
    line = line.strip()

    if ( line.isdigit() ):
        sum += 1


print( "End of file\ndata.txt contains %s lines of digits" %(sum) )

How are you running the program? Are you sure data.txt has data? Is there an empty line in the file?

try this:

while 1:
    line = file.readline()
    if not line: break
    line = line.strip()

    if ( line.isdigit() ):
        sum += 1


print( "End of file\ndata.txt contains %s lines of digits" %(sum) )
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文