0

所以我正在尝试来自https://openhatch.org/wiki/Scrabble_challenge的 ScrabbleCheat 挑战

我按照这里找到的代码,将其放入 PyCharm 中的一个项目中,但卡在了f = open(input_file, 'r')线上,说它找不到我的 sowpods.txt 文件:(

在此处输入图像描述

现在,当我从终端尝试代码时,它实际上会运行!:( 但是我正在尝试为我的项目构建一个界面,所以想尽快离开终端。

在此处输入图像描述

文本文件在正确的位置

在此处输入图像描述

问题代码,有什么想法吗?

from __future__ import print_function
from flask import Flask
import string
import sys
import sqlite3 as sqlite

app = Flask(__name__)


def test_for_db():
    # test for existance of  sowpods database
    pass


def test_for_sowpods():
    # test for existence of sowpods  text file
    pass


def word_score(input_word):
    # score the word
    # need to account for the blanks
    scores = {"a": 1, "c": 3, "b": 3, "e": 1, "d": 2, "g": 2,
            "f": 4, "i": 1, "h": 4, "k": 5, "j": 8, "m": 3,
            "l": 1, "o": 1, "n": 1, "q": 10, "p": 3, "s": 1,
            "r": 1, "u": 1, "t": 1, "w": 4, "v": 4, "y": 4,
            "x": 8, "z": 10}

    word_score = 0

    for letter in input_word:
        word_score = word_score + scores[letter]

    return word_score


def word_list(input_file):
    # create a list of tuples which containing the word, it's length, score and sorted value

    sp_list = []
    f = open(input_file, 'r')

    for line in f:
        sp_word = line.strip().lower()
        sp_list.append((sp_word, len(sp_word), ''.join(sorted(sp_word)), word_score(sp_word)))

    f.close()

    return sp_list


def load_db(data_list):

    # create database/connection string/table
    conn = sqlite.connect("sowpods.db")

    cursor = conn.cursor()
    # create a table
    tb_create = """CREATE TABLE spwords
            (sp_word text, word_len int, word_alpha text, word_score int)
            """
    conn.execute(tb_create)
    conn.commit()

    # Fill the table
    conn.executemany("insert into spwords(sp_word, word_len, word_alpha, word_score) values (?,?,?,?)",  data_list)
    conn.commit()

    # Print the table contents
    for row in conn.execute("select sp_word, word_len, word_alpha, word_score from spwords"):
        print (row)

    if conn:
        conn.close()


def print_help():
    """ Help Docstring"""
    pass


def test():
    """ Testing Docstring"""
    pass

if __name__=='__main__':
    # test()
    sp_file = "sowpods.txt"
    load_db(word_list(sp_file))
    app.run(debug=True)
4

4 回答 4

2

您正在为输入文件使用相对路径,这意味着您的脚本仅在您使用与“sowpods.txt”文件相同的工作目录运行脚本时才有效。切换到使用完整路径,因此无论脚本的工作目录是什么,您的脚本都可以正常工作。

方法如下:在if __name__=='__main__':最后的块中,而不是使用

sp_file = "sowpods.txt"

使用完整路径:

sp_file = "/Users/leongaban/scrabblechallenge/path/to/your/file/sowpods.txt"

(当然要替换文件的完整路径)

当您为程序创建 GUI 时,您可以让用户选择文件,并word_list使用生成的文件路径作为参数进行调用。

于 2013-10-18T00:38:26.817 回答
2

路径的"sowpods.txt"意思是“在任何目录中命名的文件sowpods.txt恰好是当前的工作目录”。

如果要“sowpods.txt与脚本在同一目录中命名的文件”,则必须这样说,如下所示:

import os
scriptdir = os.path.dirname(os.path.abspath(__file__))

sp_file = os.path.join(scriptdir, "sowpods.txt")

请注意,在您计划分发的实际程序或模块中,您可能需要一些更复杂的东西,您的setup.py文件为文件配置适当的(对于每台机器)位置。(您不能依赖脚本及其数据文件在大多数平台上并排安装。)


如果从命令行运行脚本,当前工作目录是显而易见的,因为您可以在 shell 中看到它。例如,在 Windows 上:

C:\> C:\Python27\python.exe C:\Users\me\MyScripts\myscript.py

…这里的当前工作目录是C:\. 为了使它工作,你必须这样做:

C:\> cd C:\Users\me\MyScripts\
C:\Users\me\MyScripts\> C:\Python27\python.exe .\myscript.py

如果您通过双击来运行该脚本,它的运行位置取决于您的操作系统和版本——它可能是您系统的根目录,或者您的主目录,或者完全是其他东西。可能没有办法让它工作。

如果您从 IDE 内部运行脚本,它可能可以由 IDE 进行配置。在 PyCharm 中,它是项目“运行/调试配置”的一部分。

但实际上,您不希望只有当您以某种方式准确地做事时才能使用的脚本。您想要一个可以运行的脚本。

于 2013-10-18T00:41:28.190 回答
1

我建议尝试以下

import os
#get the directory your script is located in which also has the file you're trying to read
path = os.path.abspath(os.path.dirname(__file__))
fullpath = os.path.join(path,input_file)
f = open(fullpath,"rt") # instead of your current open
于 2013-10-18T00:40:25.807 回答
1

Brionius 的答案有效,但当您想将脚本移动到其他地方时,它是不可移植的。

您遇到的实际上是您的 PyCharm 配置有问题。您需要更改 PyCharm 工作目录,如此所述。也就是说,您需要将工作目录更改为“sowpods.txt”当前所在的位置。

于 2013-10-18T00:40:37.343 回答