亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

要求用戶輸入文件以使用 python 運行程序

要求用戶輸入文件以使用 python 運行程序

慕森王 2021-12-08 14:42:47
我有一個程序可以連接文本中用星號分隔的法語單詞。因為我想讓這個程序被不同的用戶使用,所以我想在程序中插入一行,要求用戶輸入文本文件的路徑或者簡單地輸入文本的名稱……怎么做?只使用函數“輸入”?我不知道......有沒有一種優雅的方式讓用戶運行程序?該程序如下:import nltkfrom nltk.tokenize import word_tokenizeimport rewith open ('text-test.txt') as tx:   words = word_tokenize(tx.read().lower())with open ('Fr-dictionary.txt') as fr:    dic = word_tokenize(fr.read().lower())l=[ ]errors=[ ]out_file=open("newtext.txt","w")for n,word in enumerate (words):    l.append(word)    if word == "*":        exp = words[n-1] + words[n+1]        print("\nconcatenation error:", exp)        if exp in dic:            l.append(exp)            l.append("$")            errors.append(words[n-1])            errors.append(words[n+1])        else:           continuefor i, w in enumerate(l):    if w == "*":        l.remove(l[i-1])    else:        continuefor i, w in enumerate(l):    if w == "$":        l.remove(l[i+1])    else:        continuetext=' '.join(l)print('\n\n',text)e=len(errors)print('\n',e/2,'WORDS CONCATENATED IN TEXT',errors)user=input('\nREMOVE * AND $ FROM TEXT? Type "Y" for yes or "N" for no:')for x in l:    if user=='Y' and x=='*':        l.remove(x)    elif user=='Y' and x=='$':        l.remove(x)    else:        continuefinal_text=' '.join(l)print('\n\n', final_text)user2=input('\nWrite text to a file? Type "Y" for yes or "N" for no:')if user2 =='Y':    out_file.write(final_text)    out_file.close()    print('\nText named "newtext.txt" written to a file')
查看完整描述

2 回答

?
慕田峪4524236

TA貢獻1875條經驗 獲得超5個贊

您可以按照自己喜歡的方式進行操作,但讓用戶寫出文件的完整路徑既乏味又容易出錯。你可以做的是有一個“監視文件夾”。這是您的腳本已經知道的文件夾,甚至可能與您的腳本位于同一文件夾中。


一個小例子:


import os

import sys


# This prints the folder where the script is run.

script_directory = os.path.dirname(sys.argv[0])

print(script_directory)


# This is the folder we want to keep track off

our_watched_folder = f'{script_directory}/watch_folder'

print(our_watched_folder)


# Let's see if a user dropped a new file in our folder

print("Files in watch folder")

for file in os.listdir(our_watched_folder):

    print(file)

輸出:


C:/your_script_folder/

C:/your_script_folder/watch_folder

Files in watch folder

a_new_text_file.txt

some_old_textfile1.txt

some_old_textfile2.txt


查看完整回答
反對 回復 2021-12-08
?
Qyouu

TA貢獻1786條經驗 獲得超11個贊

from pathlib import Path

data_folder = Path(str(input("type the path you would like to use")))

file_to_open = data_folder / str(input("insert the file you would like to use with its extension"))

f = open(file_to_open)

如果您不想使用完整路徑而只想使用位于腳本位置的本地文件,您只需要詢問用戶其名稱并f = open(filename)直接打開它。


注意:如果您想知道為什么有/infile_to_open而不是字符串連接,+ 這解釋了原因。


查看完整回答
反對 回復 2021-12-08
  • 2 回答
  • 0 關注
  • 250 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號