python文本字符分析

编写程序接收字符串,按字符出现频率的降序打印字母。分别尝试录入一些中英文文章片段,比较不同语言之间字符频率的差别。

# a6.4CalLetter
txt = input("请输入一段英文片段:")
txt = txt.lower()
count = {}
for i in range(97, 123):
    count[chr(i)] = txt.count(chr(i))
items = list(count.items())
items.sort(key=lambda x: x[1], reverse=True)
for i in range(26):
    letter, cal = items[i]
    print("{:<5}{:>5}".format(letter, cal))
  • 10
    点赞
  • 83
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
Python中,可以使用字符串操作和正则表达式来进行文本字符分析。以下是一些常见的文本字符分析技术: 1. 统计字符出现次数: 可以使用Python内置函数`count()`来统计一个字符串中某个字符或子串出现的次数。例如: ```python text = "This is a sample text." count = text.count("t") print("t appears {} times in the text.".format(count)) ``` 输出结果为: ``` t appears 4 times in the text. ``` 2. 分词: 可以使用Python中的`split()`函数或者第三方库NLTK(Natural Language Toolkit)来将文本分成单词。例如: ```python text = "This is a sample text." words = text.split() print(words) ``` 输出结果为: ``` ['This', 'is', 'a', 'sample', 'text.'] ``` 3. 统计单词出现次数: 可以使用Python中的字典来统计每个单词出现的次数。例如: ```python text = "This is a sample text." words = text.split() word_count = {} for word in words: if word in word_count: word_count[word] += 1 else: word_count[word] = 1 print(word_count) ``` 输出结果为: ``` {'This': 1, 'is': 1, 'a': 1, 'sample': 1, 'text.': 1} ``` 4. 正则表达式: 正则表达式是一种用于匹配文本模式的工具。Python中可以使用re模块来进行正则表达式操作。例如: ```python import re text = "This is a sample text with some numbers: 12345" numbers = re.findall(r'\d+', text) print(numbers) ``` 输出结果为: ``` ['12345'] ``` 在上面的例子中,`\d+`是一个正则表达式,表示匹配一个或多个数字。`re.findall()`函数返回所有匹配的结果。 以上是一些常见的文本字符分析技术,当然还有很多其他的技术,具体使用取决于具体的应用场景。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值