V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
rickyleegee
V2EX  ›  Python

使用 Python 来模拟 wc 功能

  •  
  •   rickyleegee · 2019-11-01 07:51:39 +08:00 · 2869 次点击
    这是一个创建于 1637 天前的主题,其中的信息可能已经有所发展或是发生改变。

    小弟正在尝试用 python 来模拟 wc 只能使用 sys 和 argparse 不可以使用其他的库 当我输入 python3 wc.py test.txt 的时候会显示 0 1 1 test.txt -w -c -l 各种功能能正常运行 唯独单独运行 wc.py 的时候并不可 当我运行 python3 wc 的时候会允许用户输入各种字符 然后来计算最终的结果 比如: python3 wc asdfa dfaf sadfa 然后按 Ctrl D 会退出并且会显示最终结果 3 3 17 这样

    但我运行我的代码的时候会得出 0 0 0 这样的结果

    代码如下: def wc(is_l, is_w, is_c, is_m, is_L, file_list):

    ....for file in file_list:

    ......if file is "-":

    .........while True:

    ... try:

    ... f = open("test.txt", "w+")

    ... text_input = input()

    ... f.write(text_input)

    ... f.close()

    ... a = list()

    ... a.append("test.txt")

    ... b = wc(flag_l, flag_w, flag_c, flag_m, flag_L, a)

    ... if b:

    ... print(b)

    ... except (KeyboardInterrupt, EOFError):

    ... return wc_output(is_l, is_w, is_c, is_m, is_L, total_lines, total_words, total_bytes, total_chars, max_line, "")

    .. return None

    順便請問一下 怎麼可以讓這個 wc 也可以識別計算 Unicode??

    我沒有辦法發佈我完整的代碼鏈接 如需要查看我全部代碼可以留下郵箱謝謝你們

    3 条回复    2019-11-04 15:00:15 +08:00
    EscYezi
        1
    EscYezi  
       2019-11-01 12:25:54 +08:00 via iPhone
    代码可以放在 gist 上
    rickyleegee
        2
    rickyleegee  
    OP
       2019-11-01 17:38:44 +08:00
    @EscYezi 我貼不上鏈接 規定"发布这个内容需要你已经注册满 30 天" 我有上傳代碼去 gitlee 但是贴不上来 不好意思
    或者可以麻煩你去 gitlee 抖索 leegeericky / Word Count python 應該能看到我的代碼?
    InkStone
        3
    InkStone  
       2019-11-04 15:00:15 +08:00
    python3 的字符串 len 默认就是计算 unicode 长度啊……你的代码比较乱我没看明白,不过我自己测试了一下:
    >>> len("测试")
    2

    没什么问题啊。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3581 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 226ms · UTC 10:55 · PVG 18:55 · LAX 03:55 · JFK 06:55
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.