我该如何操作路径名,以便它不会打印出整个名称

时间:2019-04-11 16:37:15

标签: 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:
        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:CODE z007881 $ python3 indexed.py 在/Users/z007881/Documents/ABooks_search/CODE/booksearch/book3.t中找到9395个唯一单词 xt

我想说book3.txt中有9395个独特的单词

1 个答案:

答案 0 :(得分:0)

一种方法是在目录分隔符/上分割路径并选择最后一个元素:

file_name = txt_filename.split("/")[-1]

# ...
# Then:
print("{} unique words found in".format(len(word_keys)), file_name)

# I would prefer using an fstring, unless your Python version is too old:
print(f"{len(word_keys)} found in {file_name}")

我强烈建议将txt_filename的名称更改为不太误导的名称,例如txt_filepath,因为它不包含文件名而是整个路径(包括但不限于文件名) )。