要求用户输入一个文件以使用 Python 运行程序



我有一个程序,可以连接文本中用星号分隔的法语单词。由于我希望该程序被不同的用户使用,因此我想在程序中插入一行,要求用户输入文本文件的路径或简单地输入文本的名称...怎么做?仅使用函数"输入"?我不知道。。。有没有一种优雅的方式来要求用户运行程序?程序如下:

import nltk
from nltk.tokenize import word_tokenize
import re

with 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:
continue
for i, w in enumerate(l):
if w == "*":
l.remove(l[i-1])
else:
continue
for i, w in enumerate(l):
if w == "$":
l.remove(l[i+1])
else:
continue

text=' '.join(l)
print('nn',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:
continue

final_text=' '.join(l)
print('nn', 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')
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)打开它。

注意: 如果您想知道为什么file_to_open中有/而不是字符串连接+这解释了原因。

您可以按照自己喜欢的任何方式执行此操作,但是让用户写出文件的完整路径既乏味又容易出错。你可以做的是有一个"监视文件夹"。它是您的脚本已经知道的文件夹,甚至可能与您的脚本位于同一文件夹中。

一个小例子:

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

相关内容

  • 没有找到相关文章

最新更新