首页 > 解决方案 > 我正在尝试扫描提供的文件,并将 1 添加到每个“A”的列表中

问题描述

就像标题一样。请帮忙。最终,我想要一个能够扫描多个字母的功能。但是我的代码只是给了我一个空列表

import sys
script, filename = sys.argv
txt= open(filename)


def dna_():
    list_=[]
    a=0
    txt.read(1)
    for line in txt:
        while "A" in line:
            list_.append(a)
            a += 1
            return list_
    print (list_)
dna_()

标签: python

解决方案


所以有一个比一次读一行更好的方法来做到这一点。如果要计算字母“A”或“a”的出现次数,可以使用函数 count() 中内置的字符串。这是一个使用 python 的 License.txt 文件中第一段的示例:

A. HISTORY OF THE SOFTWARE
==========================

Python was created in the early 1990s by Guido van Rossum at Stichting
Mathematisch Centrum (CWI, see http://www.cwi.nl) in the Netherlands
as a successor of a language called ABC.  Guido remains Python's
principal author, although it includes many contributions from others.

您可以使用“readlines()”函数将整个文件读入列表:

text = open('LICENSE.txt')
lineList = text.readlines()

lineList 将如下所示:

['A. HISTORY OF THE SOFTWARE\n', '==========================\n', '\n', 'Python was created in the early 1990s by Guido van Rossum at Stichting\n', 'Mathematisch Centrum (CWI, see http://www.cwi.nl) in the Netherlands\n', "as a successor of a language called ABC.  Guido remains Python's\n", 'principal author, although it includes many contributions from others.\n']

现在您可以通过组合所有行将其更改为字符串:

myString = ''.join(lineList)

这将创建一个字符串“myString”:

"A. HISTORY OF THE SOFTWARE\n==========================\n\nPython was created in the early 1990s by Guido van Rossum at Stichting\nMathematisch Centrum (CWI, see http://www.cwi.nl) in the Netherlands\nas a successor of a language called ABC.  Guido remains Python's\nprincipal author, although it includes many contributions from others.\n"

现在要获取所有字母 'a'/'A',您可以只计算此字符串的小写实例:

aCount = myString.lower().count('a')  #this will include all the upper and lower case a's.  

最后一点,您对以下内容的使用:txt.read(1)

这只会从您的行中提取第一个字符。因此,如果文件中的第一个字母不是“a”,那么它将为空。


推荐阅读