仅替换一定数量的字符

时间:2018-04-06 05:29:14

标签: python python-3.x

我想知道是否有人可以帮助提供我目前正在努力解决的以下问题的一些见解。

假设您有一个包含以下字符的文件:

|**********|

您有另一个包含模式的文件,例如:

       -
      /-\
     /---\
    /-----\
   /-------\

您如何同时使用第一个文件中的字符替换模式中的字符? - 您只能打印第一个文件中特定数量的*。

一旦你打印完10个星,就必须停止打印。

所以它会是这样的:

    *
   ***
  *****
 *

任何提示或提示或帮助将不胜感激。

我一直在使用.replace()用'*'替换模式中的所有字符,但我无法仅打印特定的数量。

for ch in ['-', '/', '\\']:
   if ch in form:
       form = form.replace(ch, '*')

6 个答案:

答案 0 :(得分:3)

这是我的aestric文件( aestricks.txt ),其中包含:

************

图案文件( pattern.txt ),其中包含:

    -
   /-\
  /---\
 /-----\
/-------\

这里代码。我知道它可以进一步优化,但我发布了基本的:

file1 = open("aestricks.txt","r")

file1 = file1.read()

t_c = len(file1)

form = open("pattern.txt","r")

form = form.read()

form1 = form

count = 0

for ch in form1:
    if ch in ['-','/', '\\']:
        form = form.replace(ch, '*', 1)
        count += 1

    if count == t_c:
        break

for ch in form1:
    if ch in ['-','/', '\\']:
        form = form.replace(ch, '')

print(form)

<强>输出:

   *
  ***
 *****
***

答案 1 :(得分:1)

您可以使用expressions模块中的常规sub()re功能。

sub()采用可选的count参数,指示要替换的最大模式发生次数。

import re

with open('asterisks.txt') as asterisks_file, open('ascii_art.txt') as ascii_art_file:
    pattern = re.compile(r'['   # match one from within square brackets:
                         r'\\'  # either backslash
                         r'/'   # or slash
                         r'-'   # or hyphen
                         r']')

    # let n be the number of asterisks from the first file
    n = asterisks_file.read().count('*')

    # replace first n matches of our pattern (one of /\- characters)
    replaced_b = pattern.sub('*', ascii_art_file.read(), n)

    # replace rest of the /\- characters with spaces (based on your example)
    result = pattern.sub(' ', replaced_b)
    print(result)

<强>输出:

   *
  ***
 *****
*

答案 2 :(得分:0)

import re
file1 = open("file1.txt", "r") 
s=file1.read()
starcount=s.count('*')
file2 = open("file2.txt", "r") 
line = re.sub(r'[-|\\|/]', r'*', file2.read(), starcount)
line = re.sub(r'[-|\\|/]', r'', line)
print(line)

sub

的语法
>>> import re
>>> help(re.sub)
Help on function sub in module re:

sub(pattern, repl, string, count=0, flags=0)
    Return the string obtained by replacing the leftmost
    non-overlapping occurrences of the pattern in string by the
    replacement repl.  repl can be either a string or a callable;
    if a string, backslash escapes in it are processed.  If it is
    a callable, it's passed the match object and must return
    a replacement string to be used.

<强>输出

       *
      ***
     *****
    *

<强>演示

  

https://repl.it/repls/ObeseNoteworthyDevelopment

答案 3 :(得分:0)

不是一次更换每个角色,而是一次更换一个项目,并使用一些替换数量。
但str对象不支持特定索引处的项目赋值,因此您必须先将str对象转换为列表。然后执行操作并再次转换回str。 你可以写这样的东西。

characters = ['-', '/', '\\'] 
count = 0  
a = list(form)           # convert your string to list
for i in range(len(a)):
    if a[i] in characters and count < 10:   # iterate through each character
        a[i] = '*'                          # replace with '*'
        count += 1                          #  increment count
 result =  "".join(a)                       # convert list back into str
 print(result)

答案 4 :(得分:0)

import re
inp = open('stars.txt', 'r').read()
count = len(inp.strip('|')) #stripping off the extra characters from either end

pattern = open('pattern.txt', 'r').read() # read the entire pattern
out = re.sub(r'-|/|\\', r'*', pattern, count=count) # for any of the characters in '-' or '|' or '\', replace them with a '*' only **count** number of times.
out = re.sub(r'-|/|\\', r'', out) # to remove the left out characters
print (out)

添加了一个re.sub行以删除剩余的字符(如果有的话)。

答案 5 :(得分:0)

您只需跟踪输入行中*的数量,然后继续替换破折号,直到计数器用完为止。一旦计数器用完,然后用空字符串替换剩余的破折号。

def replace(p, s):
  counter = len(s) - 2
  chars = ['\\', '/', '-']
  i = 0
  for c in p:
    if c in chars:
        p = p.replace(c, '*', 1)
        i += 1
    if i == counter:
        break

  p = p.replace('\\', '')
  p = p.replace('/', '')
  p = p.replace('-', '')

  return p



if __name__ == '__main__':
  stars = '|**********|'
  pyramid = r'''
    -
   /-\
  /---\
 /-----\
/-------\ '''
  print(pyramid)
  print(replace(pyramid, stars))

<强>输出

   *
  ***
 *****
*