-3

我想打印唯一字符串值的计数、字符长度和相应的字符串。Python 很好,但我愿意接受使用其他工具的建议。如果需要特定的输出,则可以轻松解析的制表符分隔或类似的输出。这是解析 URI 参数和关键字值对的后续内容的后续内容。

示例来源:

date=2012-11-20
test=
y=5
page=http%3A//domain.com/page.html&unique=123456
refer=http%3A//domain2.net/results.aspx%3Fq%3Dbob+test+1.21+some%26file%3Dname
test=
refer=http%3A//domain2.net/results.aspx%3Fq%3Dbob+test+1.21+some%26file%3Dname
refer=http%3A//domain2.net/results.aspx%3Fq%3Dbob+test+1.21+some%26file%3Dname
y=5
page=http%3A//support.domain.com/downloads/index.asp
page=http%3A//support.domain.com/downloads/index.asp
view=month
y=5
y=5
y=5

示例输出:

5   3  y=5
3  78  refer=http%3A//domain2.net/results.aspx%3Fq%3Dbob+test+1.21+some%26file%3Dname
2  52  page=http%3A//support.domain.com/downloads/index.asp
2  5   test=
1  15  date=2012-11-20
1  10  view=month

这是一个示例,我可以使用单线,但假设在 Python 中想出一些可以处理这个和长度计数的东西可能更容易。

$ sort test | uniq -c | sort -nr
      5     y=5
      3     refer=http%3A//domain2.net/results.aspx%3Fq%3Dbob+test+1.21+some%26file%3Dname
      2     test=
      2     page=http%3A//support.domain.com/downloads/index.asp
      1     view=month
      1     page=http%3A//domain.com/page.html&unique=123456
      1     date=2012-11-20
4

1 回答 1

1

是的,您可以使用 Python 轻松完成。通常人们会倾向于使用字典来跟踪重复项

>>> from collections import defaultdict
>>> group = defaultdict(list)
>>> with open("test.txt") as fin:
    for line in fin:
        group[len(line.rstrip())].append(line)
>>> for k, g in group.items():
    print k, len(g), g[0].strip()


3 5 y=5
5 2 test=
10 1 view=month
78 3 refer=http%3A//domain2.net/results.aspx%3Fq%3Dbob+test+1.21+some%26file%3Dname
15 1 date=2012-11-20
48 1 page=http%3A//domain.com/page.html&unique=123456
52 2 page=http%3A//support.domain.com/downloads/index.asp

相反,如果您想模仿您的 shell 命令,可以使用 来实现类似的事情itertools.groupby,其行为类似于uniq

>>> with open("test.txt") as fin:
    file_it = (e.rstrip() for e in fin)
    for k, g in groupby(sorted(file_it, key = len), len):
        first_elem = next(g).strip()
        print k, sum(1 for _ in g) + 1, first_elem


3 5 y=5
5 2 test=
10 1 view=month
15 1 date=2012-11-20
48 1 page=http%3A//domain.com/page.html&unique=123456
52 2 page=http%3A//support.domain.com/downloads/index.asp
78 3 refer=http%3A//domain2.net/results.aspx%3Fq%3Dbob+test+1.21+some%26file%3Dname
于 2013-09-11T03:26:04.373 回答