繁体   English   中英

使用python解析文件以查找其中的所有回车符'\\ r'

[英]Parse a file to find all the carriage return '\r' in it using python

我有一个执行以下操作的python脚本:

1)将打印“ hi”,chr(13),chr(13),“ bi”写入文件。 2)当我执行f.read()时,在shell上看到以下内容:'hi \\ r \\ r bi'

但是,在文件中将其写为“ hi bi”。 我想做的是:计算回车符'\\ r'的数量并将其打印在shell上。 我也想用字符串“ abcde”替换子字符串“ \\ r \\ r”。 代码段: f=open('out2.txt','rb') sub='\\r\\r' print str.count(sub,1,25)

谁能建议这可以在python中完成吗?

要仅计算文件中特定字符的数量,应使用ascii模式(不是二进制模式)打开文件。

def count_str(file, s):
    ans = 0
    with open(file, 'r') as fp:
        ans = fp.read().count(s)
    return ans

如果您必须以二进制模式打开文件,则代码如下所示,

def count_str_binary(file, s):
    ans = 0
    with open(file, 'rb') as fp:
        buf = fp.read()
        bufsize = len(buf)
        length = len(s)
        for i in range(bufsize - length + 1):
            ok = True
            for j in range(length):
                if buf[i + j] != ord(s[j]):
                    ok = False
                    break
            if ok:
                ans += 1
    return ans

暂无
暂无

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

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