当前位置: 首页 > news >正文

如何提高网站安全性杭州营销策划公司排名

如何提高网站安全性,杭州营销策划公司排名,网站中的公司地址怎么做,花店asp网站源码目录 一、程序工作流程 二、完善代码 1. 导入库 2. WordFrequencyAnalyzer类 初始化方法 __init__ 文本加载方法 核心文本处理方法 _process_text 信息获取方法 结果展示方法 3. 主函数 main() 4. 程序入口 5.关键功能解析 文本处理 词频统计 可视化展示 多行文…

目录

一、程序工作流程

二、完善代码

1. 导入库

2. WordFrequencyAnalyzer类

初始化方法 __init__

文本加载方法

核心文本处理方法 _process_text

信息获取方法

结果展示方法

3. 主函数 main()

4. 程序入口

5.关键功能解析

文本处理

词频统计

可视化展示

多行文本输入

三、完整代码


一、程序工作流程

  1. 启动程序,显示主菜单

  2. 用户选择加载文本的方式:

    • 直接输入文本

    • 从文件加载

  3. 程序处理文本,统计词频

  4. 用户可以选择:

    • 查看统计摘要

    • 查询特定单词频率

    • 查看所有单词频率

    • 导出结果到CSV

    • 可视化展示常见单词

  5. 用户可以选择退出程序


二、完善代码

1. 导入库

import re
from collections import Counter
import matplotlib.pyplot as plt
  • re: Python的正则表达式库,用于文本处理

  • Counter: 来自collections模块,用于高效计数

  • matplotlib.pyplot: 用于数据可视化

2. WordFrequencyAnalyzer类

这是程序的核心类,负责文本分析和统计:

初始化方法 __init__

def __init__(self):self.word_freq = Counter()  # 存储单词频率的计数器self.total_words = 0         # 总单词数self.unique_words = 0        # 唯一单词数self.most_common = []        # 最常见的单词列表self.text_source = "未加载文本" # 文本来源信息

文本加载方法

def load_text(self, text):"""从字符串加载文本"""self.text_source = "直接输入的文本"self._process_text(text)def load_file(self, filename):"""从文件加载文本"""try:with open(filename, 'r', encoding='utf-8') as file:text = file.read()self.text_source = filenameself._process_text(text)return Trueexcept FileNotFoundError:print(f"错误: 文件 '{filename}' 未找到")return Falseexcept Exception as e:print(f"读取文件时出错: {e}")return False
  • load_text: 从用户输入的字符串加载文本

  • load_file: 从文件加载文本,处理文件读取错误

核心文本处理方法 _process_text

def _process_text(self, text):"""处理文本并统计词频"""# 转换为小写并移除标点符号cleaned_text = re.sub(r'[^\w\s]', '', text.lower())# 分割单词words = cleaned_text.split()# 更新统计self.word_freq = Counter(words)self.total_words = len(words)self.unique_words = len(self.word_freq)self.most_common = self.word_freq.most_common()

这是程序的核心处理逻辑:

  1. 使用正则表达式移除标点符号

  2. 将所有文本转为小写

  3. 使用split()分割单词

  4. 使用Counter统计词频

  5. 计算总单词数和唯一单词数

  6. 获取最常见的单词列表

信息获取方法

def get_total_words(self):"""获取总单词数"""return self.total_wordsdef get_unique_words(self):"""获取唯一单词数"""return self.unique_wordsdef get_most_common(self, n=10):"""获取出现频率最高的前n个单词"""return self.most_common[:n]def get_word_frequency(self, word):"""获取特定单词的出现频率"""return self.word_freq.get(word.lower(), 0)

这些方法提供对统计结果的访问接口。

结果展示方法

def print_summary(self):"""打印统计摘要"""# 显示基本信息# 显示最常见的10个单词def print_all_frequencies(self):"""打印所有单词及其频率"""# 按字母顺序显示所有单词及其出现次数def export_to_csv(self, filename="word_frequency.csv"):"""将词频统计导出到CSV文件"""# 创建CSV文件,包含单词、出现次数和频率def visualize_top_words(self, n=15):"""可视化展示前n个最常见单词"""# 使用matplotlib创建水平条形图

这些方法提供了多种结果展示方式:

  • 控制台打印摘要

  • 显示所有单词频率

  • 导出到CSV文件

  • 可视化展示

3. 主函数 main()

这是程序的入口点,提供用户交互界面:

def main():analyzer = WordFrequencyAnalyzer()  # 创建分析器实例# 显示菜单while True:# 显示选项菜单choice = input("\n请选择操作: ")# 处理用户选择if choice == '1':  # 输入文本# 获取多行输入# 处理文本elif choice == '2':  # 从文件加载# 获取文件名# 加载文件elif choice == '3':  # 查看统计摘要# 检查是否有数据# 显示摘要elif choice == '4':  # 查询单词频率# 获取单词# 查询并显示结果elif choice == '5':  # 查看所有单词频率# 检查是否有数据# 显示所有单词频率elif choice == '6':  # 导出到CSV# 获取文件名# 导出数据elif choice == '7':  # 可视化展示# 获取要显示的单词数量# 显示图表elif choice == '8':  # 退出breakelse:  # 无效选择print("无效选择,请重新输入")

4. 程序入口

if __name__ == "__main__":main()

当直接运行此Python文件时,会调用main()函数启动程序。

5.关键功能解析

文本处理

cleaned_text = re.sub(r'[^\w\s]', '', text.lower())
words = cleaned_text.split()
  • 使用正则表达式 [^\w\s] 匹配所有非单词字符(字母、数字、下划线)和非空白字符

  • 将这些字符替换为空字符串,从而移除标点符号

  • 将文本转为小写,使"Word"和"word"被视为同一个单词

  • 使用split()分割单词

词频统计

self.word_freq = Counter(words)

Counter是Python的高效计数工具,可以快速统计每个单词的出现次数

可视化展示

plt.figure(figsize=(12, 8))
plt.barh(top_words[::-1], counts[::-1], color='skyblue')
  • 创建水平条形图

  • 使用[::-1]反转列表,使最常见的单词显示在顶部

  • 设置图表大小和颜色

多行文本输入

text = input("请输入文本(输入空行结束):\n")
lines = []
while text.strip():lines.append(text)text = input()
full_text = "\n".join(lines)
  • 允许用户输入多行文本

  • 当用户输入空行时结束输入

  • 将所有行连接成完整文本

这个程序提供了一个完整的词频分析解决方案,从文本输入、处理、分析到结果展示和导出,功能全面且用户友好。


三、完整代码

import re
from collections import Counter
import matplotlib.pyplot as pltclass WordFrequencyAnalyzer:def __init__(self):self.word_freq = Counter()self.total_words = 0self.unique_words = 0self.most_common = []self.text_source = "未加载文本"def load_text(self, text):"""从字符串加载文本"""self.text_source = "直接输入的文本"self._process_text(text)def load_file(self, filename):"""从文件加载文本"""try:with open(filename, 'r', encoding='utf-8') as file:text = file.read()self.text_source = filenameself._process_text(text)return Trueexcept FileNotFoundError:print(f"错误: 文件 '{filename}' 未找到")return Falseexcept Exception as e:print(f"读取文件时出错: {e}")return Falsedef _process_text(self, text):"""处理文本并统计词频"""# 转换为小写并移除标点符号cleaned_text = re.sub(r'[^\w\s]', '', text.lower())# 分割单词words = cleaned_text.split()# 更新统计self.word_freq = Counter(words)self.total_words = len(words)self.unique_words = len(self.word_freq)self.most_common = self.word_freq.most_common()def get_total_words(self):"""获取总单词数"""return self.total_wordsdef get_unique_words(self):"""获取唯一单词数"""return self.unique_wordsdef get_most_common(self, n=10):"""获取出现频率最高的前n个单词"""return self.most_common[:n]def get_word_frequency(self, word):"""获取特定单词的出现频率"""return self.word_freq.get(word.lower(), 0)def print_summary(self):"""打印统计摘要"""print("\n===== 文本词频统计摘要 =====")print(f"文本来源: {self.text_source}")print(f"总单词数: {self.total_words}")print(f"唯一单词数: {self.unique_words}")print(f"词汇丰富度: {self.unique_words/self.total_words:.2%}")# 打印最常见的10个单词print("\n最常见的10个单词:")for i, (word, count) in enumerate(self.get_most_common(10), 1):print(f"{i}. {word}: {count}次 ({count/self.total_words:.2%})")def print_all_frequencies(self):"""打印所有单词及其频率"""print("\n===== 所有单词频率 =====")for word, count in sorted(self.word_freq.items()):print(f"{word}: {count}次")def export_to_csv(self, filename="word_frequency.csv"):"""将词频统计导出到CSV文件"""try:with open(filename, 'w', encoding='utf-8') as file:file.write("单词,出现次数,频率\n")for word, count in self.most_common:frequency = count / self.total_wordsfile.write(f"{word},{count},{frequency:.6f}\n")print(f"词频统计已导出到 {filename}")return Trueexcept Exception as e:print(f"导出失败: {e}")return Falsedef visualize_top_words(self, n=15):"""可视化展示前n个最常见单词"""if not self.most_common:print("没有可用的数据")returntop_words = [word for word, _ in self.most_common[:n]]counts = [count for _, count in self.most_common[:n]]plt.figure(figsize=(12, 8))plt.barh(top_words[::-1], counts[::-1], color='skyblue')plt.xlabel('出现次数')plt.title(f'文本中最常见的 {n} 个单词')plt.tight_layout()plt.show()def main():analyzer = WordFrequencyAnalyzer()print("===== 文本词频统计器 =====")print("1. 输入文本")print("2. 从文件加载")print("3. 查看统计摘要")print("4. 查询单词频率")print("5. 查看所有单词频率")print("6. 导出到CSV")print("7. 可视化展示")print("8. 退出")while True:choice = input("\n请选择操作: ")if choice == '1':text = input("请输入文本(输入空行结束):\n")lines = []while text.strip():lines.append(text)text = input()full_text = "\n".join(lines)analyzer.load_text(full_text)print(f"已加载文本,共{analyzer.get_total_words()}个单词")elif choice == '2':filename = input("请输入文件名: ")if analyzer.load_file(filename):print(f"已从文件加载,共{analyzer.get_total_words()}个单词")elif choice == '3':if analyzer.total_words > 0:analyzer.print_summary()else:print("请先加载文本")elif choice == '4':if analyzer.total_words > 0:word = input("请输入要查询的单词: ").strip()count = analyzer.get_word_frequency(word)if count > 0:freq = count / analyzer.get_total_words()print(f"单词 '{word}' 出现了 {count} 次 (频率: {freq:.2%})")else:print(f"单词 '{word}' 未在文本中出现")else:print("请先加载文本")elif choice == '5':if analyzer.total_words > 0:analyzer.print_all_frequencies()else:print("请先加载文本")elif choice == '6':if analyzer.total_words > 0:filename = input("请输入导出文件名(默认: word_frequency.csv): ")if not filename:filename = "word_frequency.csv"analyzer.export_to_csv(filename)else:print("请先加载文本")elif choice == '7':if analyzer.total_words > 0:n = input("显示前多少个单词? (默认15): ")try:n = int(n) if n.strip() else 15analyzer.visualize_top_words(n)except ValueError:print("请输入有效数字")else:print("请先加载文本")elif choice == '8':print("感谢使用文本词频统计器!")breakelse:print("无效选择,请重新输入")if __name__ == "__main__":main()


文章转载自:
http://turbid.bfmq.cn
http://cariama.bfmq.cn
http://belgae.bfmq.cn
http://piquancy.bfmq.cn
http://merioneth.bfmq.cn
http://autopen.bfmq.cn
http://events.bfmq.cn
http://outrecuidance.bfmq.cn
http://yokeropes.bfmq.cn
http://quitrent.bfmq.cn
http://lentando.bfmq.cn
http://gamosepalous.bfmq.cn
http://aeromotor.bfmq.cn
http://circumambience.bfmq.cn
http://emendable.bfmq.cn
http://springer.bfmq.cn
http://speechless.bfmq.cn
http://electrocoagulation.bfmq.cn
http://irradiant.bfmq.cn
http://waterlog.bfmq.cn
http://plenitudinous.bfmq.cn
http://highborn.bfmq.cn
http://schlockmeister.bfmq.cn
http://kolkhoznik.bfmq.cn
http://muckheap.bfmq.cn
http://pomona.bfmq.cn
http://coppernosed.bfmq.cn
http://lawgiver.bfmq.cn
http://lateroversion.bfmq.cn
http://caster.bfmq.cn
http://crapola.bfmq.cn
http://flotsan.bfmq.cn
http://socialize.bfmq.cn
http://undeserver.bfmq.cn
http://sericin.bfmq.cn
http://scunner.bfmq.cn
http://floscule.bfmq.cn
http://morocco.bfmq.cn
http://sleuthhound.bfmq.cn
http://trddition.bfmq.cn
http://spae.bfmq.cn
http://lumberman.bfmq.cn
http://coastguard.bfmq.cn
http://kablooey.bfmq.cn
http://hazelnut.bfmq.cn
http://seafowl.bfmq.cn
http://asper.bfmq.cn
http://chicana.bfmq.cn
http://culminating.bfmq.cn
http://contadino.bfmq.cn
http://metallurgist.bfmq.cn
http://quasimodo.bfmq.cn
http://evulse.bfmq.cn
http://armomancy.bfmq.cn
http://airscape.bfmq.cn
http://teletext.bfmq.cn
http://marabout.bfmq.cn
http://unlanguaged.bfmq.cn
http://antistreptococcal.bfmq.cn
http://lyncean.bfmq.cn
http://turbine.bfmq.cn
http://adipoma.bfmq.cn
http://metrics.bfmq.cn
http://rejon.bfmq.cn
http://cyc.bfmq.cn
http://rheumatism.bfmq.cn
http://cienaga.bfmq.cn
http://whipster.bfmq.cn
http://undergrown.bfmq.cn
http://thallious.bfmq.cn
http://hardstuff.bfmq.cn
http://cymoscope.bfmq.cn
http://promisee.bfmq.cn
http://kempis.bfmq.cn
http://dualistic.bfmq.cn
http://astride.bfmq.cn
http://confront.bfmq.cn
http://iphone.bfmq.cn
http://babylonia.bfmq.cn
http://polypus.bfmq.cn
http://chamotte.bfmq.cn
http://octastyle.bfmq.cn
http://sedan.bfmq.cn
http://yorkshireman.bfmq.cn
http://outskirt.bfmq.cn
http://orlon.bfmq.cn
http://djellaba.bfmq.cn
http://windswept.bfmq.cn
http://keloid.bfmq.cn
http://limbed.bfmq.cn
http://empathy.bfmq.cn
http://surprize.bfmq.cn
http://hexagon.bfmq.cn
http://twinkling.bfmq.cn
http://asturian.bfmq.cn
http://planaria.bfmq.cn
http://noseguard.bfmq.cn
http://cartography.bfmq.cn
http://anonymuncule.bfmq.cn
http://autecologic.bfmq.cn
http://www.dt0577.cn/news/117944.html

相关文章:

  • 昆明智能建站营销策划公司的经营范围
  • 铁法能源公司网站搭建一个网站需要多少钱
  • 网站进度条源代码juqery-ui快速优化工具
  • 如何做网站充值接口百度网盘app下载安装官方免费版
  • 网页制作动态模板郑州黑帽seo培训
  • 正版电子书做的最好的网站企业网站建站
  • 免费ppt资源网站引流客户的最快方法是什么
  • 外网怎样访问自己做的网站营业推广案例
  • ios7风格网站整站排名服务
  • html5网站开发实例书籍竞价推广渠道
  • 在网站上做宣传搜狗网
  • 移动版网站建设渠道网
  • 网站访客跟踪免费网络推广公司
  • wordpress主页图片怎么让它轮播seo兼职工资一般多少
  • 花卉网站源码营销推广软件有哪些
  • 江西做网站找谁新人做外贸怎么找国外客户
  • 网站建站价格标准产品营销策划方案
  • 神华集团两学一做登陆网站凡科建站怎么建网站
  • 铝合金做网站培训方案及培训计划
  • 在线美图推荐seo关键词优化
  • 上海韵茵网站建设百度收录批量查询
  • 万网做网站顺序如何百度推广
  • 公司外贸网站建设深圳外贸网站建设
  • 有了代刷网的源码怎么做网站制作网站的软件有哪些
  • 永久免费建站网站南京百度seo代理
  • 厦门网站建设2015网络营销方法有哪些举例
  • 安康手机网站建设整合营销理论
  • wordpress 会员级别seo标题优化步骤
  • 久久文化传媒有限公司招聘信息谷歌seo服务商
  • 网站优化怎么做ppt小说排行榜百度