reader read()==-1中文问题

在某次处理reader中,该流中含有中文字符,代码如下

		Reader r = null;
		try
		{
			char c = (char) r.read();
			while ((byte) c == -1)
			{
				// Do ...
				c = (char) r.read();
			}
		} catch (IOException e)
		{
			e.printStackTrace();
		}

发现读不完整中文字符,原来是int->char的问题,正确处理应该如下

		Reader r = null;
		try
		{
			int i =r.read();
			char c=(char)i;
			while (i == -1)
			{
				// Do ...
				
				i =  r.read();
				c=(char)i;
			}
		} catch (IOException e)
		{
			e.printStackTrace();
		}

测试代码

 int i=65535;
//		 int i=-1;
		 char c=(char)i;
		 byte b=(byte)c;
		 int i2=(int)c;
		 System.out.println("int:"+i+",->char:"+c+" ,char->byte:"+b+" ,char->int: "+i2);

结果可以看到:

int:65535,->char: ,char->byte:-1 ,char->int: 65535
int:-1,->char: ,char->byte:-1 ,char->int: 65535



#加载模块 import csv import os import re import jieba import pandas as pd #设置读取情感词典的函数 def read_dict(file): my_dict=open(file).read() wordlist=re.findall(r'[\u4e00-\u9fa5]+',my_dict) return wordlist positive=read_dict('C:/Users/xiaomei/Desktop/reports/positive.txt') negative=read_dict('C:/Users/xiaomei/Desktop/reports/negative.txt') #读取csv文件,并进行处理 results={} with open('C:/Users/xiaomei/Desktop/report.csv', 'r', encoding='utf-8') as f: reader=csv.reader(f) for row in reader: text=row[2] text=re.sub(r'[^\u4e00-\u9fa5]+',' ',text) words=jieba.cut(text) #自定义情感分析函数 def senti_count(text): wordlist1=jieba.lcut(text) wordlist1=[w for w in wordlist1 if len(w)>1] positive_count=0 for positive_word in positive: positive_count=positive_count+wordlist1.count(positive_word) negative_count=0 for negative_word in negative: negative_count=negative_count+wordlist1.count(negative_word) return {'word_num':len(wordlist1),'positive_num':positive_count,'negative_num':negative_count} #生成保存路径 csvf=open('C:/Users/xiaomei/Desktop/情感分析.csv','w',encoding = 'gbk',newline = '') writer=csv.writer(csvf) writer.writerow(('公司名称','年份','总词汇数','正面情感词汇数','负面情感词汇数')) senti_score=senti_count(text) word_num = senti_score['word_num'] positive_num = senti_score['positive_num'] negative_num = senti_score['negative_num'] writer.writerow((company,year,word_num,positive_num,negative_num)) csvf.close()
06-08
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值