定义文件名并在各种循环和函数中调用文件名

简而言之,我已经编写了一个代码来打开文件并对其进行许多修改。但是,当我要打开新文件时,我不想一直浏览脚本并重命名所有文件。

我正在考虑尽早设置一个定义文件名的变量,即

A=filename('png1.png')
B=filename('png2.png')

但是,我不太了解如何实现此目标。这是我当前的代码:

import os

from os import path
import numpy as np
from PIL import Image
from wordcloud import WordCloud,STOPWORDS

#d=path.dirname(_file_) if "_file_" in locals() else os.getcwd()
os.chdir('C:/Users/Sams PC/Desktop/Word_Cloud_Scripts/Dmitrys Papers/Word_Cloud_Dmitry')
Document=open('Dmitry_all_lower.txt','r',encoding='utf-8')
text=Document.read()

heart_mask=np.array(Image.open("**png1.png**"))
print (heart_mask)
split= str('**png1.png**').rsplit('.')
extension=split[len(split)-1]
if extension == "png":
    image = Image.open("**png1.png**")
    image.convert("RGBA") # Convert this to RGBA if possible

    canvas = Image.new('RGBA',image.size,(255,255,255)) # Empty canvas colour (r,g,b,a)
    canvas.paste(image,mask=image) # Paste the image onto the canvas,using it's alpha channel as mask
    #canvas.thumbnail([width,height],Image.ANTIALIAS)
    canvas.save('**png2.png**')

    from wand.image import Image

    with Image(filename='**png2.png**') as img:
        img.format='jpeg'
        img.save(filename='**png1.jpg**')
    from PIL import Image
    heart_mask=np.array(Image.open("**png1.jpg**"))
else:
    print ('')


print (heart_mask)
stopwords=set(STOPWORDS)
stopwords.update(["will","us","protein","residue","interaction","residues","using","proteins","thus","fig"])
wc= WordCloud(stopwords=stopwords,background_color="white",max_words=1000,mask=heart_mask,contour_width=3,contour_color='black')
print ('Generating Word Cloud')

wc.generate(text)
wc.to_file("Dmitry3.png")

import matplotlib.pyplot as plt
plt.figure()
plt.imshow(wc,interpolation="bilinear")
plt.axis("off")
print ('Generation Done')
plt.show()

我把整个事情都只是为了看看发生了什么,但是我已经加粗了(在旁边加星号),这些都是我想要修改的文件。如您所见,我有多个调用文件“ png1.png”的调用,还有一些调用来将文件的修改后的版本保存为“ png2.png”,然后将其保存为jpeg版本的“ png1.jpg”。我不想每次都遍历我的脚本并单独更改每个脚本。我希望可以更早地定义它们,例如A = png1,B = png2,C = jpg1,这样我就可以用AB和C替换循环中的调用,并且如果我选择要上传的新图像,只需更改1或2行,而不是5或6行。IE

heart_mask=np.array(Image.open("A"))
split= str('A').rsplit('.')
image = Image.open("A")
canvas.save('B')
... so on and so forth
andys740813 回答:定义文件名并在各种循环和函数中调用文件名

为了使您的任务更容易,也许您应该建立一个命名标准,定义要修改的文件已经处理的文件。另外,要处理的图像应具有专用的目录。

据我了解,在您的代码中,PNG文件是经过处理的文件,而JPEG文件已经完成。您可以使用os.listdir()遍历具有.png扩展名的文件列表,类似于以下文件:

for file in os.listdir( "/dedicated_image_dir" ):
    if file.endswith(".png"):
        # Process your PNG images here

这样,您甚至不需要更改代码即可容纳不同文件名的新PNG图片。

本文链接:https://www.f2er.com/3147735.html

大家都在问