程序员文章、书籍推荐和程序员创业信息与资源分享平台

网站首页 > 技术文章 正文

Python统计文本数量

hfteth 2025-03-11 16:21:48 技术文章 20 ℃
import re

def count_texts(file_content):
    # 移除注释
    file_content = re.sub(r'-.*
, '', file_content, flags=re.MULTILINE) # 初始化变量 texts = [] current_text = "" in_string = False string_char = None # 用于标记当前字符串的引号类型(单引号或双引号) i = 0 while i < len(file_content): char = file_content[i] # 处理字符串 if in_string: if char == string_char and (i == 0 or file_content[i-1] != '\\'): in_string = False string_char = None current_text += char i += 1 else: if char in ('"', "'"): in_string = True string_char = char current_text += char i += 1 elif char == ';': if current_text.strip(): # 忽略空文本 texts.append(current_text.strip()) current_text = "" i += 1 else: current_text += char i += 1 # 处理最后一条文本(可能没有分号) if current_text.strip(): texts.append(current_text.strip()) return len(texts) # 从标准输入读取多行内容 def main(): print("请输入文件内容(输入空行结束):") file_content = [] while True: line = input() if line.strip() == "": # 输入空行结束 break file_content.append(line) file_content = "\n".join(file_content) # 将多行内容合并为一个字符串 # 统计文本数量 result = count_texts(file_content) print("文本数量:", result) # 主程序 if __name__ == "__main__": main()


Tags:

最近发表
标签列表