Qt如何提取文件中的中文

一、背景介绍

    在实际项目中,我们会用到需要把批量文件中的中文提取出来,提供给翻译人员,再由它们翻译之后,导入到目标文件中。现在就以一个.xml格式的文件为例,解释如何实现提取方法,以及用到Qt中哪些库。
    提取中文源文件内容如下:

<example type="af">
	<testnode name="我的名字是HelloWord" pos="top" role="0" number="1号">
	</testnode>
</example >

二、方法实现

    提取的方法很简单,用一个正则表达式来判断就可以实现。提取出来的中文条目,用QStringList返回。

QStringList getMatchingList(const QString& filePath, const QStringList& rexList)
{
	QFile _inputFile(filePath);
	if (!_inputFile.open(QIODevice::ReadOnly | QIODevice::Text))
	{
		qDebug() << "Open file " + _inputFile.fileName() + "failed.";
		return QStringList();
	}
	QTextStream _in(&_inputFile);
	//输出文件:存储查找结果
	QFile outputFile("output.txt");
	outputFile.open(QIODevice::WriteOnly);
	QTextStream out(&outputFile);

	_in.setCodec(QTextCodec::codecForName("utf-8"));//必须加,否则含有中文时乱码
	QString txtStr = _in.readAll();
	//如果要区分大小写,就把下面这句话删掉
	//txtStr.toLower();

	QRegExp regExp;
	int pos, result;
	pos = result = 0;	
	//将匹配设置为最小(短)匹配
	regExp.setMinimal(true);
	
	QStringList _matchList;
	for (int i = 0; i < rexList.count(); i++)
	{
		regExp.setPattern(rexList.at(i));
		pos = 0;
		//开始匹配
		while ((pos = regExp.indexIn(txtStr, pos)) != -1)
		{
			QString str = regExp.cap(1);

			QRegularExpression re;
			re.setPattern("[\u4e00-\u9fa5]");
			if (str.contains(re))
			{
				_matchList.append(str);
				out << str << endl;
			}
			pos += regExp.matchedLength();
			result++;
		}
	}

	qDebug() << result << " results" << endl;
	_inputFile.close();
	outputFile.close();
	return _matchList;
}

    其中参数filePath表示导入的文件所在路径,rexList表示正则表达式的集合,比如像xml格式的文档,我们提取的中文,应该是来自属性值,就是双引号里面的值,我们就可以定义这样一个正则表达式:\“(.*)\”,这个正则表达式就表示提取双引号里面的所有内容。

    使用这个函数提取的结果就是:
    我的名字是HelloWord,1号

三、参考资料

  1. QT:利用正则表达式查找文本
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值