简体   繁体   English

PYTHON(2.7):列表理解-在带有其他文本的.txt文件中添加(和)数字

[英]PYTHON(2.7): List comprehension - Adding(sum) numbers in a .txt file with additional text

I'm trying to make this code run a certain way. 我正在尝试使此代码以某种方式运行。 I'm trying to make it so there is a text file I have with both words and numbers in. The code needs to extract either positive or negative numbers and then add them together. 我正在尝试制作一个文本文件,同时包含单词和数字。代码需要提取正数或负数,然后将它们加在一起。 Below, I have an example of what it looks like in the text file minus the bullet points. 在下面,我有一个示例,说明文本文件减去项目符号后的外观。 I'm trying to make it the shortest amount of code(as any code should be written) using list comprehension. 我正在尝试使用列表理解使它成为最短的代码量(因为应该编写任何代码)。 I'm still a novice coder, so any help is appreciated. 我仍然是新手编码人员,因此可以提供任何帮助。


example of text and numbers in file

 - Positive 36
 - Negative: -12
 - Negative: -11
 - Positive: 42
 - Positive: 95
 - Negative: -4

Here is a rough attempt of code. 这是代码的粗略尝试。 I'm having most trouble (in theory) trying to implement whether I want to grab positive or negative numbers: 从理论上讲,我遇到最大的麻烦是尝试实现我要获取正数还是负数:

    sum([int(line.strip()) for line in open("text.txt").readlines()])

split on whitespace and get the second element which is the integer: 在空格上分割并获取第二个元素,该元素是整数:

with open("text.txt") as f: # using with closes your files automaticlly
    print sum([int(line.split()[1]) for line in f.readlines()])
146

You can also just iterate over the file object without using readlines: 您也可以不使用readlines遍历文件对象:

with open("out.txt") as f:
   print sum([int(line.split()[1]) for line in f])

If you used print ([line.split() for line in f]) the output would look like: 如果使用print ([line.split() for line in f]) ,输出将如下所示:

 [['Positive', '36'], ['Negative:', '-12'], ['Negative:', '-11'], ['Positive:', '42'], ['Positive:', '95'], ['Negative:', '-4']]

so you can see how line.split()[1] gets the integer. 因此您可以看到line.split()[1]如何获取整数。

You can determine the sign of the number from just the number, so split each line and grab the last part: 您可以仅从数字中确定数字的符号,因此将每一行分开并抓住最后一部分:

with open('text.txt') as handle:
    numbers = (int(line.split()[1]) for line in handle)

total = sum(n for n in numbers if n > 0)

There's no need to call readlines on the file object, as iterating over the file object itself gives you all of the lines one at a time. 不需要在文件对象上调用readlines ,因为对文件对象本身进行遍历可以一次给所有行。 Also, using a generator expression uses two less characters and will work faster for larger text files, as there's no intermediate list. 另外,使用生成器表达式时,使用的字符减少了两个,并且由于没有中间列表,因此对于较大的文本文件,其运行速度也更快。

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

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