【问题标题】:Simple text cleaning python 3.6 script not giving correct output on executing the script using cmd prompt on windows 10简单的文本清理 python 3.6 脚本在 Windows 10 上使用 cmd 提示符执行脚本时没有给出正确的输出
【发布时间】:2018-03-17 17:22:34
【问题描述】:

当我在spyder 上执行此脚本时,它运行完美,但当我通过 Windows 10 机器上的命令提示符执行脚本时,相同的脚本没有给出正确的输出。我的机器上有 python 3.6 和 anaconda 3.6。这真是奇怪的行为。我也尝试在 ubuntu 系统上执行脚本,但也没有得到正确的输出。

clean_data.py

import re
import argparse

def main(data):
    if data.strip():
        data = data.strip()
        emoji_pattern = re.compile("["
                "\U0001F600-\U0001F64F"  # emoticons
                "\U0001F000-\U0001F5FF"  # symbols & pictographs
                "\U0001F680-\U0001F6FF"  # transport & map symbols
                "\U0001F1E0-\U0001F1FF"  # flags (iOS)
                "\U0001F900-\U0001F9FF"  # extra emoticons
                "\U00002600-\U000026FF"
                "\U00002700-\U000027BF"
                "\U00002B00-\U00002BFF"
                "\U00003000-\U000032FF"
                "\U000025A0-\U000025FF"
                "\U000024C2-\U0001F251"
                "\U000020D0-\U000120FF"
                "\U00000000-\U0000001a"
                "]+", flags=re.UNICODE)
        data = emoji_pattern.sub("", data)
        data = re.sub("[^A-Za-z0-9 !@#$%^&*()_+=-}]{[|\':;?/>.<,]", "", data).encode("ascii", "ignore").decode("utf-8")
        print(data)
    else:
        print("Empty string!!")

#main("     ")
#main("i'm deciding between Firestik Firefly, 4' \u2248\u001a200w, \n\r& Firestik FS-3BK, 3' \u2248\u001a650w. Is one better? It's for recreational use on and off road. thank you!")

if __name__ == '__main__':
    parser = argparse.ArgumentParser(
    description = __doc__,
    formatter_class = argparse.RawDescriptionHelpFormatter)
    parser.add_argument('data', help = 'Simply the text that you want to clean.')
    args = parser.parse_args()
    main(args.data)

要重现,请将脚本另存为“clean_data.py”

要执行脚本打开终端并输入:

python clean_data.py "我在 Firestik Firefly, 4' \u2248\u001a200w, \n\r& Firestik FS-3BK, 3' \u2248\u001a650w 之间做出选择。哪个更好?它是用于娱乐用途的开关路。谢谢!”

预期的输出是:

我在 Firestik Firefly,4' 200w 和 Firestik FS-3BK,3' 650w 之间做出选择。一个更好吗?它适用于公路和越野的娱乐用途。谢谢!

【问题讨论】:

  • 在 OS X python 3.6 上转载。
  • 你通过终端@cdarke得到正确的输出了吗?
  • 命令提示符不会将 \u2248 例如转换为 Unicode 字符。它实际上是六个 ASCII 字符。那是 Python 语法,不是 shell 语法。
  • @ShubhamChandra:不,我得到的输出和你一样。
  • 嘿@MarkTolonen 谢谢你的解释。真的很有帮助。

标签: python regex python-3.x unicode windows-10


【解决方案1】:

cmd shell 不理解 Python 的 Unicode 转义序列,因此您会收到转义码的文字 ASCII 字符。

如果您想支持翻译它们,您可以将main 调用更改为:

main(args.data.encode(sys.stdin.encoding).decode('unicode-escape'))

然后你的输出将是:

i'm deciding between Firestik Firefly, 4' 200w, & Firestik FS-3BK, 3' 650w. Is one better? It's for recreational use on
and off road. thank you!

【讨论】:

  • 非常感谢@MarkTolonen 提供此解决方案。它清楚地解释了一切,最重要的是,它奏效了!
猜你喜欢
  • 2017-12-29
  • 1970-01-01
  • 2022-01-17
  • 2023-02-15
  • 2017-08-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-27
相关资源
最近更新 更多