看到C++一题目 :
本书配套提供了一个名为babynames2004.txt。。。
。
。
本书配套提供了一个名为babynames2004.txt。。。
然后我就琢磨了半天写出来了:
#include <fstream>
#include <iostream>
#include <cstdlib>
#include<cstring>
#include<string>
using namespace std;
//date:20160116
void babyname(ifstream& in_stream, ofstream& out_stream,string x);
int main( )
{
ifstream fin;
ofstream fout;
string x;
cout << "Begin editing files.\n";
fin.open("babynames2004.txt");
if (fin.fail( ))
{
cout << "Input file opening failed.\n";
exit(1);
}
cout<<"输入你要搜索的名字:\n" ;
cin>>x;
babyname(fin, fout,x);
fin.close( );
fout.close( );
cout << "End of editing files.\n";
return 0;
}
void babyname(ifstream& in_stream, ofstream& out_stream, const string x){
int i=0,g=1;
string next;
string num[1001],two[1001],three[1001],a[1001];
// if(!in_stream.eof()) {
// getline(in_stream,num[i]);
// i++;
// for(i;i<1000;i++){
// getline(in_stream,num[i]);
// }
// }
while(in_stream>>next){
if(g%3==1)
{
num[i]=next;
}
if(g%3==2)
{
two[i]=next;
}
if(g%3==0)
{
three[i]=next;
i++;
}
g++;
}
int flag1=0,flag2=0;
//cout<<"num999:"<<num[999]<<"two4:"<<two[4]<<"three88:"<<three[88];
for(int i=0;i<1001;i++){
string s=static_cast<string> (two[i]);
if(x==s)
{
flag1=1;
cout<<x<<" is ranked "<<num[i]<<" boys."<<endl;
}
}
if(flag1==0)
cout<<x<<" is not ranked among the top 1000 boy names.";
for(int i=0;i<1001;i++){
string s=static_cast<string> (three[i]);
if(x==s){
flag2=2;
cout<<x<<" is ranked "<<num[i]<<" girls."<<endl;
}
}
if(flag2==0)
cout<<x<<" is not ranked among the top 1000 girl names.\n";
}
。
。
但是用Python写这个程序可不同了 太简单 :
# -*- coding: cp936 -*-
#20160117
c=[]
v=[]
b=[]
a=[]
try:
x=open("babynames2004.txt",'r')
i=0
for foreach in x:
a=foreach[:-1].split(" ")
c.append(a[0])
v.append(a[1])
b.append(a[2])
i=i+1
x.close()
except IOError,e:
print 'file open error:',e
print "请输入你要搜索的姓名: "
d=raw_input("> ")
i=0
flag1=0
flag2=0
for i in range(1000):
if d==v[i]:
flag1=1
print d+" is ranked "+c[i]+" boys.";
if flag1==0:
print d+" is not ranked among the top 1000 boy names";
for i in range(1000):
if d==b[i]:
flag2=1
print d+" is ranked "+c[i]+" boys.";
if flag2==0:
print d+" is not ranked among the top 1000 girl names";
。
。