Python 3.x 如何操作路径名,使其不受';不要把全名打印出来
我是编程新手。我需要索引三个单独的txt文件。并从输入进行搜索。当我打印时,它会给我整个路径名。我想打印txt文件名 我正在尝试在函数中使用os.listPython 3.x 如何操作路径名,使其不受';不要把全名打印出来,python-3.x,string-formatting,Python 3.x,String Formatting,我是编程新手。我需要索引三个单独的txt文件。并从输入进行搜索。当我打印时,它会给我整个路径名。我想打印txt文件名 我正在尝试在函数中使用os.list import os import time import string import os.path import sys word_occurrences= {} def index_text_file (txt_filename,ind_filename, delimiter_chars=",.;:!?"): try:
import os
import time
import string
import os.path
import sys
word_occurrences= {}
def index_text_file (txt_filename,ind_filename, delimiter_chars=",.;:!?"):
try:
txt_fil = open(txt_filename, "r")
fileString = txt_fil.read()
for word in fileString.split():
if word in word_occurrences:
word_occurrences[word] += 1
else:#
word_occurrences [word] = 1
word_keys = word_occurrences.keys()
print ("{} unique words found in".format(len(word_keys)),txt_filename)
word_keys = word_occurrences.keys()
sorted(word_keys)
except IOError as ioe: #if the file can't be opened
sys.stderr.write ("Caught IOError:"+ repr(ioe) + "/n")
sys.exit (1)
index_text_file("/Users/z007881/Documents/ABooks_search/CODE/booksearch/book3.txt","/Users/z007881/Documents/ABooks_search/CODE/booksearch/book3.idx")
SyntaxError:无效语法
(基本)8c85908188d1:代码z007881$python3.py
在/Users/z007881/Documents/ABooks_search/CODE/booksearch/book3.t中找到9395个唯一单词
xt
我想让它说出在book3.txt中找到的9395个独特单词一种方法是在目录分隔符上拆分路径,然后选择最后一个元素:
file\u name=txt\u filename.split(“/”[-1]
# ...
#然后:
打印(“{}在“.format(len(word\u keys))、文件名中找到的唯一单词)
#我更喜欢使用fstring,除非您的Python版本太旧:
打印(在{file\u name}中找到{len(word\u key)})
我强烈建议您将
txt\u filename
的名称改成像txt\u filepath
这样误导性较小的名称,因为它不包含文件名,而是包含整个路径(包括但不限于文件名)。请格式化您的代码好吗?突出显示所有内容,然后按[code>CTRL+K问题的[code>format行中的选项在我看来很好。但是,您移动了参数,您在这里显示的行将完全忽略文件名。哦,您是对的。我不知道我在想什么。