bingbingyihao 2021-10-01 12:02 采纳率: 100%
浏览 29
已结题

python如何每次读两个汉字,读取字符,为了实验,无法读取两个字符(自然语言处理)



def getText():
    txt=open('Ci.txt','r',encoding ="utf-8").read()
    for ch in '\n \ / ,。、:!?”“#¥%':
        txt=txt.replace(ch,"")
    return txt

test=getText()

counts={}

for word in test:
    if len(word)==1:
        if word in counts:
            counts[word]=counts[word]+1
        else:
            counts[word]=1

items=list(counts.items())
items.sort(key=lambda x:x[1],reverse=True)

with open('2.txt','w') as a:
    a.write(str(items))

文件就不上传了,就是无法读取两个字符(汉字),只能读出单个汉字,但是又不想用jieba包,如何处理,求解决方案

  • 写回答

1条回答 默认 最新

  • 关注

    你这样每次读两个:

    def getText():
        txt = open('1.txt', 'r', encoding="utf-8").read()
        for ch in '\n \ / ,。、:!?”“#¥%':
            txt = txt.replace(ch, "")
        return txt
    
    test = getText()
    print(test)
    counts = {}
    for i in range(len(test)-1):
        t=test[i]+test[i+1]
        if len(t) == 2:
            if t in counts:
                counts[t] = counts[t] + 1
            else:
                counts[t] = 1
    items = list(counts.items())
    print(items)
    items.sort(key=lambda x: x[1], reverse=True)
    with open('2.txt', 'w') as a:
        a.write(str(items))
    

    img

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

问题事件

  • 系统已结题 10月9日
  • 已采纳回答 10月1日
  • 创建了问题 10月1日

悬赏问题

  • ¥15 怎样才能让鼠标沿着线条的中心线轨迹移动
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?