我有一个包含450,000多行条目的文件.每个条目的长度约为7个字符.我想知道的是这个文件的独特字符.
例如,如果我的文件如下;
Run Code Online (Sandbox Code Playgroud)Entry ----- Yabba Dabba Doo
那么结果就是
独特人物:{abdoy}
注意我不关心案例,也不需要订购结果.有些东西告诉我这对Linux人来说很容易解决.
我正在寻找一个非常快速的解决方案.我真的不想创建代码来遍历每个条目,遍历每个字符......等等.我正在寻找一个很好的脚本解决方案.
通过快速的,我的意思是快速实现......不一定运行速度快.
Jay*_*Jay 17
BASH shell脚本版本(没有sed/awk):
while read -n 1 char; do echo "$char"; done < entry.txt | tr [A-Z] [a-z] | sort -u
Run Code Online (Sandbox Code Playgroud)
更新:只是为了它,因为我很无聊并仍在思考这个问题,这里是一个使用set的C++版本.如果运行时间很重要,这将是我推荐的选项,因为C++版本需要稍微超过半秒来处理具有450,000多个条目的文件.
#include <iostream>
#include <set>
int main() {
std::set<char> seen_chars;
std::set<char>::const_iterator iter;
char ch;
/* ignore whitespace and case */
while ( std::cin.get(ch) ) {
if (! isspace(ch) ) {
seen_chars.insert(tolower(ch));
}
}
for( iter = seen_chars.begin(); iter != seen_chars.end(); ++iter ) {
std::cout << *iter << std::endl;
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
请注意,我忽略了空格,并且它根据请求不区分大小写.
对于450,000+条目文件(chars.txt),这是一个示例运行时:
[user@host]$ g++ -o unique_chars unique_chars.cpp
[user@host]$ time ./unique_chars < chars.txt
a
b
d
o
y
real 0m0.638s
user 0m0.612s
sys 0m0.017s
Run Code Online (Sandbox Code Playgroud)
Joa*_*uer 10
根据要求,一个纯shell脚本"解决方案":
sed -e "s/./\0\n/g" inputfile | sort -u
Run Code Online (Sandbox Code Playgroud)
这不好,它不快,输出不完全如规定,但它应该工作......主要是.
为了更加荒谬,我提出了将输出转储到一行的版本:
sed -e "s/./\0\n/g" inputfile | sort -u | while read c; do echo -n "$c" ; done
Run Code Online (Sandbox Code Playgroud)
使用set数据结构.大多数编程语言/标准库都有一种或另一种.如果他们不这样做,请使用哈希表(或通常是字典)实现,只省略值字段.使用您的角色作为键.这些数据结构通常会过滤掉重复的条目(因此名称set来自其数学用法:集合没有特定的顺序,只有唯一的值).
Python w/sets(快速而肮脏)
s = open("data.txt", "r").read()
print "Unique Characters: {%s}" % ''.join(set(s))
Run Code Online (Sandbox Code Playgroud)
Python w/sets(具有更好的输出)
import re
text = open("data.txt", "r").read().lower()
unique = re.sub('\W, '', ''.join(set(text))) # Ignore non-alphanumeric
print "Unique Characters: {%s}" % unique
Run Code Online (Sandbox Code Playgroud)
快速而肮脏的C程序非常快:
#include <stdio.h>
int main(void)
{
int chars[256] = {0}, c;
while((c = getchar()) != EOF)
chars[c] = 1;
for(c = 32; c < 127; c++) // printable chars only
{
if(chars[c])
putchar(c);
}
putchar('\n');
return 0;
}
Run Code Online (Sandbox Code Playgroud)
编译它,然后做
cat file | ./a.out
Run Code Online (Sandbox Code Playgroud)
获取一个独特的可打印字符列表file.
这是一个PowerShell示例:
gc file.txt | select -Skip 2 | % { $_.ToCharArray() } | sort -CaseSensitive -Unique
Run Code Online (Sandbox Code Playgroud)
其产生:
迪亚博
我喜欢它很容易阅读。
编辑:这是一个更快的版本:
$letters = @{} ; gc file.txt | select -Skip 2 | % { $_.ToCharArray() } | % { $letters[$_] = $true } ; $letters.Keys
Run Code Online (Sandbox Code Playgroud)