【问题标题】:Reading text file using sys.stdin使用 sys.stdin 读取文本文件
【发布时间】:2019-03-03 00:37:51
【问题描述】:

我有一个简单的程序:

import sys
import string

stopWordsPath = sys.argv[1]
delimitersPath = sys.argv[2]
stopWordsList = []
delimiterList = []

with open(stopWordsPath) as f:
    for line in f:
        line = line.strip()
        stopWordsList.append(line)

with open(delimitersPath) as f:
delimiterList = f.read().strip()

for line in sys.stdin:
    print line

当我尝试在 linux 中做这样的事情时:

python TitleCountMapper.py stopwords.txt delimiters.txt | input.txt

它一直挂在我身上。我正在使用标准输入,因为这是需要输入的方式。这是传递txt文件以便stdin可以读取的正确方法吗?

【问题讨论】:

    标签: python stdin python-2.x


    【解决方案1】:

    | 表示将前面程序的输出作为输入引导到后面的程序,而不是将后面的文件的输入提供给前面的程序。

    您应该使用< 而不是|

    python TitleCountMapper.py stopwords.txt delimiters.txt < input.txt
    

    【讨论】:

      【解决方案2】:

      管道的工作方式相反:

      cat input.txt | python TitleCountMapper.py stopwords.txt delimiters.txt
      

      或者更好的是,使用 &lt; 进行 I/O 重定向:

      python TitleCountMapper.py stopwords.txt delimiters.txt <input.txt
      

      【讨论】:

        猜你喜欢
        • 2014-03-05
        • 1970-01-01
        • 2010-11-27
        • 2012-05-26
        • 2012-09-04
        • 2016-02-16
        • 2016-04-17
        • 2013-04-12
        • 2020-03-21
        相关资源
        最近更新 更多