引言:之前做c++作业时遇到了一个棘手的问题,就是去除文件中相同的元素,由于文件很大,这个功能用c++实现起来就比较复杂,就想到用python实现,但由于学术不精,只能利用c++程序调动cmd运行python程序
一、引入头文件
#include<stdio.h>
#include<stdlib.h>
#include<string>
#include<iostream>
using namespace std;
二、函数实现
void Python()
{
char result[100];
FILE *fp;
string cmd = "python test.py"; //字符串类型变量,赋值为要cmd执行的命令
/*c_str()方法实现字符串在cmd命令行的输入
_popen()函数以只读方式获取命令行返回结果*/
fp = _popen(cmd.c_str(),"r");
if(fp == NULL)
{
cout << "ERROR" << endl;
exit(1);
}
/*fgets(result,sizeof(result)-1,fp)从命令行读取一行信息写入result中*/
while(fgets(result,sizeof(result)-1,fp)!=NULL)
{
cout << result;
}
_pclose(fp); //关闭命令行窗口
}
三、用于测试的python文件test.py
print("")
'''该处输出为空,则程序显示error
可通过try-except方式,脚本异常输出空与c++程序传递信息'''
四、python实现文本元素去重复
filename1 = "idword1.txt"
filename2 = "idword2.txt"
seqars = []
with open(filename1) as file_object:
for line in file_object :
'''按行读取文件内容,装入seqars列表'''
seqars.append(line)
'''利用set()函数将列表转化为集合,去除重复元素
再用list函数将集合转化为列表'''
seq = list(set(seqars))
with open(filename2,'w') as file_object2:
for word in seq:
'''按行写入文档'''
file_object2.write(word)
print("")