【问题标题】:Sum strings length from a txt file [duplicate]对txt文件中的字符串长度求和[重复]
【发布时间】:2020-11-09 21:35:32
【问题描述】:

我有一个 txt 文件,其名称如下:

Hans
Anna
Vladimir
Michael
Ed
Susan
Janice
Jo

我想打印所有名字长度的总和:

with open(r"C:\people_names.txt", "r") as name_file:
    sum_names = (len(x) for x in name_file)
print(sum(sum_names))

问题是每个名字后面都有“\n”,算作字母,而姓氏没有“\n”,

这就是为什么我不能len(x)-1

如果您有任何计算方法的建议将很高兴:)

【问题讨论】:

    标签: python python-3.x file sum string-length


    【解决方案1】:

    如果文件太大,我不建议使用readlines()
    您可以使用rstrip 删除每行末尾的\n

    with open(r"C:\people_names.txt", "r") as name_file:
        sum_names = [len(x.rstrip('\n')) for x in name_file]
    print(sum(sum_names))
    

    【讨论】:

    • 谢谢!听起来不错!
    • 您是否尝试运行此代码?它返回错误。
    • @RoshinRaphel 感谢您的注意,我更新了答案 sum_names 是之前导致问题的生成器
    【解决方案2】:
    with open(r"C:\people_names.txt", "r") as name_file:
        data = name_file.read()  
    
    total_characters = len(data) - data.count("\n")
    print(total_characters)
    

    【讨论】:

      【解决方案3】:

      从文件中读取每一行:

      with open(r"C:\people_names.txt", "r") as name_file:
          name_file = name_file.readlines()
      sum_names = [len(x.strip()) for x in name_file]
      print(sum(sum_names))
      

      name_file.readlines() 返回行列表,这些行由换行符标识。这将解决您的问题。 另一种解决方案是使用splitlines()

      with open(r"hello.txt", "r") as name_file:
          name_file = name_file.read().splitlines()
      sum_names = [len(x) for x in name_file]
      print(sum(sum_names))
      

      【讨论】:

      • 非常感谢!所以如果我使用len(x.strip() 方法,我不必做name_file = name_file.readlines()
      • @Ileh 那么你将不得不使用 name_file = name_file.read() 因为with 会自动关闭文件处理程序,使其下一行无法访问
      猜你喜欢
      • 2017-08-19
      • 1970-01-01
      • 1970-01-01
      • 2020-05-30
      • 2014-05-16
      • 2015-10-21
      • 2012-05-22
      • 2012-10-23
      相关资源
      最近更新 更多