繁体   English   中英

python:文件i / o计数字符没有新行

[英]python: file i/o counting characters without new lines

我有一个名为number.txt的文本文件。 它包含以下内容:

0
1
2
3

我的代码:

def main():
   inFile = open("number.txt", "r")
   text = inFile.read() 
   inFile.close()
   print(len(text))
main()

我试图使用上面的代码打印出文件中有多少个字符。 它打印出8,但只有4个字符。 我知道当python读入文件时,它会在每行之后添加换行符,这可能是额外的字符。 我怎么摆脱这个?

该文件在每行之间包含换行符。 要将其过滤掉,您可以重新创建字符串而不使用replacesplit或类似的换行符,或者计算换行符并从长度中减去它们(这样更快/更有效)。

with open("number.txt", "r") as file:
    text = file.read()
length_without_newlines = len(text) - text.count('\n')

编辑:正如@lvc所说,Python将所有行结尾转换为'\\ n'(0x0A),包括windows换行符('\\ r \\ n'或[0x0D,0x0A]),因此只需搜索'\\ n'时寻找新的线条字符。

正如安东尼奥在评论中所说,新行字符在文件中。 如果你愿意,你可以删除它们:

def main():
   inFile = open("number.txt", "r")
   text = inFile.read() 
   inFile.close()
   text = text.replace('\n', '')  # Replace new lines with nothing (empty string).
   print(len(text))
main()

你的脚本的答案是正确的:实际上新行也是字符(它们只是不可见!)

要省略新行字符(在字符串中用\\n\\r\\n引用),则必须用空字符串替换它们。

看到这段代码:

def main():
   inFile = open("number.txt", "r")
   text = inFile.read()
   text = text.replace("\r\n","") #in windows, new lines are usually these two 
   text = text.replace("\n","")   

caracters。 inFile.close()print(len(text))main()

有关\\r\\n\\n是什么的更多信息,请尝试: http//en.wikipedia.org/wiki/Newline

使用string.rstrip('\\n') 这将删除字符串右侧的换行符,而不是其他内容。 请注意,无论平台如何,python都应将所有换行符转换为\\n 我还建议迭代文件的行,而不是将它全部转储到内存中,以防你有一个大文件。

示例代码:

if __name__ == '__main__':
   count = 0
   with open("number.txt", "r") as fin):
       for line in fin:
           text = line.rstrip('\n')
           count += len(text)
   print(count)

尝试这个:

if __name__ == '__main__':
    with open('number.txt', 'rb') as in_file:
        print abs(len(in_file.readlines()) - in_file.tell())

在打印行中执行此操作,如下所示:

    print(len(text.replace("\n", "")))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM