以下是使用Python实现的一个例子:
import os
import sys
from collections import Counter
def count_words(file_name):
count = Counter()
with open(file_name, 'r') as f:
for line in f:
words = line.strip().split()
count.update(words)
return count
def main(result_file):
path = os.getcwd()
count = Counter()
for file_name in os.listdir(path):
if file_name.startswith('a') and file_name.endswith('.txt'):
count.update(count_words(file_name))
with open(result_file, 'w') as f:
for word, freq in count.most_common():
f.write(f'{word}\t{freq}\n')
if __name__ == "__main__":
if len(sys.argv) != 2:
print('Usage: python yifan-online-countfiles.py OUTPUT_FILE')
sys.exit(1)
main(sys.argv[1])
这个脚本分别实现了三个函数:
count_words(file_name),该函数用于读取一个文件并统计其中单词的频率。
main(result_file),该函数是主函数,用于查找当前目录下所有以字母a开头并以.txt结尾的文件并统计其中单词的频率,然后将结果写入指定的文件。
脚本的入口点,当脚本被执行时,获取命令行参数中的输出文件名并调用main()函数。如果没有提供正确的命令行参数,显示使用说明并退出。
使用这个脚本时,可以在命令行上运行 python yifan-online-countfiles.py r2.txt ,其中r2.txt是存放词频统计结果的文件名。
... 展开详请
既然你的坐标属于成对的,为什么不为他们写一个结构呢?
struct CoordinatePai
{
int x;
int y;
};
然后你可以为istreams写一个重载的提取操作符:
std::istream& operator>>(std::istream& is, CoordinatePair& coordinates)
{
is >> coordinates.x >> coordinates.y;
return is;
}
然后你可以直接读取一个坐标文件,像这样的矢量:
#include <fstream>
#include <iterator>
#include <vector>
int main()
{
char filename[] = "coordinates.txt";
std::vector<CoordinatePair> v;
std::ifstream ifs(filename);
if (ifs) {
std::copy(std::istream_iterator<CoordinatePair>(ifs),
std::istream_iterator<CoordinatePair>(),
std::back_inserter(v));
}
else {
std::cerr << "Couldn't open " << filename << " for reading\n";
}
// Now you can work with the contents of v
}... 展开详请