繁体   English   中英

我在 Python For Everyone 第 1.8 节和终端使用方面遇到问题

[英]I am having issues with Python For Everyone Section 1.8 and terminal usage

好的,所以在我永无止境地重新开始学习数据科学的过程中,我正在重新学习 Python 的精髓,并通过 Python 的《Everybody Book》。

我目前停留在涉及使用终端的第 1.8 节。 它要求我在终端中使用 Python 程序来扫描文本文件。 这本书提供了我应该用于本节的 python 代码和文本文件。 我已经创建了 Python 程序和文本文件,并将它们都放在我的桌面上,因此在同一个文件中。

文件中的 Python 程序如下所列,命名为words.py

name = input('Enter file:')
handle = open(name, 'r')
counts = dict()

for line in handle:
    words = line.split()
    for word in words:
        counts[word] = counts.get(word, 0) + 1

bigcount = None
bigword = None
for word, count in list(counts.items()):
    if bigcount is None or count > bigcount:
        bigword = word
        bigcount = count

print(bigword, bigcount)

我创建的文本文件包含以下文本,名为clowntext.txt

the clown ran after the car and the car ran into the tent
and the tent fell down on the clown and the car 

现在,文件clowntext.txtwords.py再次位于我桌面上的同一个文件夹中。 因此,当我在终端中运行 Python 程序时,为什么终端会提示我没有指定名称的文件? 我在终端中看到的整个代码块都在下面的代码中。

Last login: Mon Nov 29 06:33:44 on ttys000
(base) wayneshaw@Waynes-MacBook-Air ~ % python Desktop/words.py
Enter file:clowntext.txt
Traceback (most recent call last):
  File "/Users/wayneshaw/Desktop/words.py", line 2, in <module>
    handle = open(name, 'r') 
FileNotFoundError: [Errno 2] No such file or directory: 'clowntext.txt'

此外,如果这是描述终端使用的错误元素,我深表歉意。 这是我在 StackOverflow 上的第一个问题。

您的程序正在当前目录中查找文件~ ,但clowntext.txt~/Desktop中。

虽然程序与输入文件位于同一文件夹中,但您从不同的文件夹启动程序(您的输入文件在~/Desktop中,但您从~启动它),并且程序没有从程序所在的文件夹 ( ~/Desktop ),但来自程序启动的文件夹 ( ~ )。

你可以给你的程序一个完整的路径, Desktop/clowntext.txt ,或者将clowntext.txt移动到~

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM