Python 当前执行文件路径拆分和拼接

# encoding=utf-8
import sys,os,time

# 一:在系统搜索路径添加指定路径,当前执行路径默认会加入系统搜索路径

sys.path.append(os.path.abspath(os.path.split(os.path.abspath(__file__))[0]+"\\.."))
print({"sys.path":sys.path})

# {'sys.path': ['E:\\Python\\argv_getopt_argpara','E:\\Python']}
# E:\\Python\\argv_getopt_argpara:当前文件执行路径
# E:\\Python:人为指定搜索路径

# 解析理解如下:

# 1,获取当前文件绝对路径

file_abspath = os.path.abspath(__file__)
print({"file_abspath":file_abspath})

#{'file_abspath': 'E:\\Python\\argv_getopt_argpara\\argv.py'}

# 2,将文件名和路径分开,os.path.split返回的是一个元组<class 'tuple'>

cur_file_path, file_name = os.path.split(file_abspath)
print({"cur_file_path":cur_file_path, "file_name":file_name})

# {'cur_file_path': 'E:\\Python\\argv_getopt_argpara', 'file_name': 'argv.py'}

# 3,获取当前文件路径的上一级目录

cur_file_parent_path = os.path.abspath(cur_file_path + "\\..")
print({"cur_file_parent_path":cur_file_parent_path})

# {'cur_file_parent_path': 'E:\\Python'}

# 二:文件路径拼接方法

# 1,获取当前执行文件所在目录相对路径

cur_exec_file_path = os.path.dirname(__file__)

print({"cur_exec_file_path":cur_exec_file_path})

# {'cur_exec_file_path': ''}

tm_year, tm_mon, tm_mday, _, _, _, _, _, _ = time.localtime()
csv_name = os.path.join(cur_exec_file_path, "{}-{}-{}-test.csv".format(str(tm_year).zfill(4), str(tm_mon).zfill(2), str(tm_mday).zfill(2)))

print({"csv_name":csv_name})

# {'csv_name': '2022-04-23-test.csv'}

# 三:多行字符串拆分成文件路径

代码实现:

# -*- coding:utf-8 -*-

from pathlib import Path
from os.path import abspath

pathString = """
D:\Edisk\python\BatchRename
D:\BaiduNetdiskDownload\day18
D:\BaiduNetdiskDownload\day19_多线程
"""

def stringToPath(s):
    print("****************abspath(s)******************")
    print('abspath(s)原始字符串:', s)
    print('abspath(s)绝对路径为:', [abspath(s)])
    print('abspath(s)绝对路径为:', abspath(s))

    print("\n****************Path(s)*********************")
    path = Path(s)
    print('Path(s)转为路径后:', [path])
    print('Path(s)转为路径后:', path)
    print('Path(s)再转回字符串:', [str(path)])
    print('Path(s)再转回字符串:', str(path))

if __name__ == '__main__':
    paths = pathString.split('\n')
    for path in paths[1:-1]:
        print("="*40)
        stringToPath(path)
        print("\n")
        

打印结果:

 

要进行Python大量文件的词频统计,可以参考以下步骤: 1. 首先,需要遍历整个文件夹,获取所有文件路径。可以使用os模块中的os.walk()函数来实现这一步骤。 2. 对于每个文件,可以使用文件操作和字符串处理来读取文件内容并进行词频统计。可以使用codecs模块来读取文件,使用正则表达式或字符串分割来拆分文本内容为单词。 3. 创建一个字典来存储每个单词及其出现的频率。在遍历文件时,对于每个单词,如果字典中已存在,则将其计数加1;如果字典中不存在,则将其添加到字典中,并初始计数为1。 4. 对字典按照单词频率进行排序,可以使用sorted函数并结合lambda表达式来实现。 5. 可以选择输出前N个频率最高的单词及其频率,这里设定N为10。可以使用切片操作来获取字典中前N个元素。 下面是一个示例代码,演示了如何实现Python大量文件的词频统计: ```python import os import codecs import re # 定义文件路径 folder_path = './folder' # 定义字典用于存储单词及其出现的频率 word_freq = {} # 遍历文件夹中的所有文件 for root, dirs, files in os.walk(folder_path): for file in files: # 拼接文件路径 file_path = os.path.join(root, file) # 读取文件内容 with codecs.open(file_path, 'r', encoding='utf-8') as f: content = f.read() # 使用正则表达式或字符串分割将文本内容拆分为单词 words = re.findall(r'\b\w+\b', content.lower()) # 统计单词频率 for word in words: if word in word_freq: word_freq[word += 1 else: word_freq[word = 1 # 对字典按照单词频率进行排序 sorted_word_freq = sorted(word_freq.items(), key=lambda x: x<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [python实现简单中文词频统计示例](https://download.csdn.net/download/weixin_38739101/13772666)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"] - *2* [python文件词频统计](https://download.csdn.net/download/weixin_43332900/12109517)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"] - *3* [python实现TXT文件批量处理-分割、翻译和格式转excel](https://download.csdn.net/download/qq_41970674/88274911)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值