Python 读取文件并显示该文件中的名称总和
我希望最后的代码执行的是读取名为“names.txt”的文本文档中的一个名称字符串。然后告诉程序计算该文件中有多少个名称,并显示名称的数量。到目前为止,我使用的代码是要在文本文件中显示数字的总和,但它与我现在需要的程序非常接近,因此我认为我可以重新编写它,以收集字符串/名称的数量,并显示它,而不是总和 以下是迄今为止的代码:Python 读取文件并显示该文件中的名称总和,python,file,Python,File,我希望最后的代码执行的是读取名为“names.txt”的文本文档中的一个名称字符串。然后告诉程序计算该文件中有多少个名称,并显示名称的数量。到目前为止,我使用的代码是要在文本文件中显示数字的总和,但它与我现在需要的程序非常接近,因此我认为我可以重新编写它,以收集字符串/名称的数量,并显示它,而不是总和 以下是迄今为止的代码: def main(): #initialize an accumulator. total = 0.0 try: # Open t
def main():
#initialize an accumulator.
total = 0.0
try:
# Open the file.
myfile = open('names.txt', 'r')
# Read and display the file's contents.
for line in myfile:
amount = float(line)
total += amount
# Close the file.
myfile.close()
except IOError:
print('An error occured trying to read the file.')
except ValueError:
print('Non-numeric data found in the file.')
except:
print('An error occured.')
# Call the main function.
main()
我对Python编程还是个新手,所以请不要对我太苛刻。如果有人能想出如何重做,以显示数字/名称的数量,而不是数字的总和。我将不胜感激。如果这个程序不能被修改,我很乐意接受一个新的解决方案
编辑:这是“names.txt”的示例:
约翰
玛丽
保罗
安
或者你也可以
fh=open("file","r")
print "%d words"%len(fh.read().split())
fh.close()
所有这些都是现成的信息,如果你付出一些努力,这些信息并不难找到……仅仅获得答案通常会导致不及格的课程……考虑到文本文件中的名称是由行分隔的
myfile = open('names.txt', 'r')
lstLines = myfile.read().split('\n')
dict((name,lstLines.count(name)) for name in lstLines)
这将为每个名称创建一个字典,每个名称都有其出现次数
在列表中搜索特定名称(如“name1”)的出现情况
lstLines.count('name1')
假设名称使用空格分隔:
def main():
#initialize an accumulator.
total = 0.0
try:
# Open the file.
myfile = open('names.txt', 'r')
# Read and display the file's contents.
for line in myfile:
words = line.split()
total += len(words)
# Close the file.
myfile.close()
except IOError:
print('An error occured trying to read the file.')
except ValueError:
print('Non-numeric data found in the file.')
except:
print('An error occured.')
# Call the main function.
main()
如果您只想计算文件中的行数
# Open the file.
myfile = open('names.txt', 'r')
#Count the lines in the file
totalLines = len(myfile.readlines()):
# Close the file.
myfile.close()
使用with语句打开文件。即使发生异常,它也会正确关闭文件。您可以省略文件模式,这是默认模式
如果每个名称都在其自己的行中且没有重复项:
with open('names.txt') as f:
number_of_nonblank_lines = sum(1 for line in f if line.strip())
name_count = number_of_nonblank_lines
任务很简单。从新代码开始,以避免累积问题代码的未使用/无效代码
如果您只需要对wc-l命令等文件中的行进行计数,则可以使用.count'\n'方法:
另请参见,名称是否分别位于不同的行?这是家庭作业吗?此外,名称是如何分隔的?是否每一行都有自己的行,是否用分号分隔?逗号?没有足够的信息来回答这个问题。那么你试着改变什么使它与名字和计数一起工作呢?尝试更改它并使其工作,然后返回这里,询问有关新代码和哪些代码不工作的具体问题。+1至@arxanas。此外,您是否正在尝试计算文件中名称的数量,或文件中唯一名称的数量。如果每行1个名称,最好使用wc-l names.txt或sort-u names.txt | wc-l@inspectorG4dget这是,这是不允许的。可以使用chunk.count'\n'而不是.readlines来计算文件中的行数,请参阅。2.要计算符合某些条件的行数,可以使用生成器:而无需像.readlines那样将整个文件加载到内存中。
with open('names.txt') as f:
number_of_nonblank_lines = sum(1 for line in f if line.strip())
name_count = number_of_nonblank_lines
#!/usr/bin/env python
import sys
from functools import partial
read_chunk = partial(sys.stdin.read, 1 << 15) # or any text file instead of stdin
print(sum(chunk.count('\n') for chunk in iter(read_chunk, '')))