如何获取“字符串”的数量(?)和普林

2024-05-16 13:46:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个不同单词的列表,在.txt中用“:”分隔,例如:

banana:pinapple
apple:grapes
orange:nuts
...

如何获得分号左边有单词的行数并打印该数字?你知道吗

我用这个把它们分开:

string1, string2 = line.split(':')

我想把数字打印成这样:

print(number of lines where there exists is a string1)

Tags: txtapple列表line数字单词splitbanana
3条回答
count = 0
for line in f:
    string1, string2 = line.split(':')
    if string1:
        count += 1
print(count)

你的问题是关于左边的字数,这正是它的意义所在。这将处理行为:foo的情况。不过,您还没有提出过有没有没有没有冒号的行或有多个冒号的行。另外,你还没说过左边会有一个以上的单词。我选择忽略这些案例,因为你没有指出它们的存在。你知道吗

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)

猫myfile.txt文件

banana:pinapple
apple:grapes
orange:nuts
banana:pinapple
apple:grapes
orange:nuts
banana:pinapple
apple:grapes
orange:nuts

结果

{'banana':3,'apple':3,'orange':3}

所以,我不确定我是否理解你的问题,根据所有提供的答案。你只想知道如何计算文本文件中的行数?你知道吗

是的,我看到你说“在冒号左边有一个单词”,但是为什么你要在没有其他文本的行上有一个冒号呢?你说你的程序写文本的方式是“示例”:“示例”对吧?你知道吗

如果是这样的话,你就不会有一个冒号在一行没有任何其他文本,除非你故意输入什么,这仍然是一些东西。你知道吗

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

如果你想去掉一个单词或冒号,可以很容易地调整它来完成。你知道吗

相关问题 更多 >