python - 我正在尝试扫描提供的文件,并将 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_()
解决方案
所以有一个比一次读一行更好的方法来做到这一点。如果要计算字母“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”,那么它将为空。
推荐阅读
- c# - 多个按钮不同的属性循环
- asp.net-core - 更新用户声明而不更新身份验证时间
- mysql - 使用建议单词而不是结果的 MySQL 全文搜索自动完成
- vba - ADODB.Stream ReadText 无法正常工作
- html - chrome 开发者工具中的图标
- domain-driven-design - 在 DDD 聚合根中,应该在哪里放置检查现有聚合的逻辑
- firebase - 如何同步获取 Firebase 消息令牌
- javascript - 从我的实时数据库中检索数据的函数中的代码不会触发其他 window.alerts
- facebook - 我什么时候需要提交我的应用以供 Facebook 审核(当只有少数人会使用它时)?
- smarty - 节循环以错误的索引/值开始