import re
import random
def writeInFile(fileName, tab): //This function writes the answer in a file
i = 0
with open(fileName, 'a') as n:
while i != len(tab):
n.write(str(tab[i]))
if i + 1 != len(tab):
n.write(' ')
i += 1
n.write('\n');
def main():
file = open('file.txt', 'r').readlines() //Reading the file containing the digits
tab = re.findall(r'\d+', str(file)) //Getting every number using regexp, in string file, and put them in a list.
randomDigit = random.randint(0, 100) // Generating a random integer >= 0 and <= 100
numberToReplace = "4" //Manually setting number to replace
for i in xrange(len(tab)): //Browsing list, and replacing every "4" to the randomly generated integer.
if tab[i] == str(numberToReplace):
tab[i] = str(randomDigit)
writeInFile("output.txt", tab) //Call function to write the results.
if __name__ == "__main__":
main()
下面是一个可以帮助您的python示例:
示例:
你知道吗文件.txt包含:
4 14 4 444 20
你知道吗输出.txt将是:
60 14 60 444 20
,考虑到随机生成的整数是60
。你知道吗重要提示:在本例中,我认为您的文件只包含正数。因此,您必须修改regexp以获得负数,如果您有数字以外的字符,则需要对其进行一点更改。你知道吗
这可能不是你需要的方式,但我认为这是一个好的开始。你知道吗
相关问题 更多 >
编程相关推荐