fileName = 'myfile.txt'
counterDict = {}
with open(fileName,'r') as fh:
for line in fh:
left,right = line.rstrip('\n').split(':')
counterDict[left] = counterDict.get(left,0)+1
print(counterDict)
def get_total_lines(self, path):
counter = 0
try:
if os.path.isfile(path):
with open(path, 'r') as inFile:
for i in enumerate(inFile):
counter = counter + 1
return str(counter)
elif not os.path.isfile(path):
print("Error: The file you're attempting to read does not exist, aborting reading process...")
except IOError as exception:
raise IOError('%s: %s' % (path, exception.strerror))
return None
这是一些基本的错误检查形式,这里有一个没有。你知道吗
def get_total_lines(self, path):
counter = 0
with open(path, 'r') as inFile:
for i in enumerate(inFile):
counter = counter + 1
return str(counter) # could be int or w/e else you want it to be
你的问题是关于左边的字数,这正是它的意义所在。这将处理行为
:foo
的情况。不过,您还没有提出过有没有没有没有冒号的行或有多个冒号的行。另外,你还没说过左边会有一个以上的单词。我选择忽略这些案例,因为你没有指出它们的存在。你知道吗猫myfile.txt文件
结果
所以,我不确定我是否理解你的问题,根据所有提供的答案。你只想知道如何计算文本文件中的行数?你知道吗
是的,我看到你说“在冒号左边有一个单词”,但是为什么你要在没有其他文本的行上有一个冒号呢?你说你的程序写文本的方式是“示例”:“示例”对吧?你知道吗
如果是这样的话,你就不会有一个冒号在一行没有任何其他文本,除非你故意输入什么,这仍然是一些东西。你知道吗
这是一些基本的错误检查形式,这里有一个没有。你知道吗
如果你想去掉一个单词或冒号,可以很容易地调整它来完成。你知道吗
相关问题 更多 >
编程相关推荐