简体   繁体   English

将字符或单词移到新行

[英]Move a character or word to a new line

Given a string how do i move part of the string in to a new line.给定一个字符串,我如何将字符串的一部分移到新行中。 without moving the rest of the line or characters不移动其余的行或字符

'This' and 'this' word should go in the next line
Output:
> and word should go in the next line
  This this

This is just an example of the output i want assuming the words can be different by characters.这只是我想要的输出示例,假设单词可以因字符而异。 To be more clear say i have some string elements in an array and i have to move every second and third word of the elements to a new line and printing the rest of the line as is.更清楚地说,我在数组中有一些字符串元素,我必须将元素的每第二个和第三个单词移动到一个新行并按原样打印该行的其余部分。 I've tried using \\n and a for loop.我试过使用 \\n 和 for 循环。 But it also moves the rest of the string to a new line但它也会将字符串的其余部分移动到一个新行

['This and this', 'word should go', 'in the next']
Output:
> This word in
  and this should go the next

So the 2nd and 3rd word of the elements are moved without affecting the rest of the line.因此,移动元素的第 2 个和第 3 个字而不会影响该行的其余部分。 Is it possible to do this without much complication?是否有可能在没有太多复杂性的情况下做到这一点? I'm aware of the format method but i don't know how to use it in this situation.我知道 format 方法,但我不知道在这种情况下如何使用它。

For your first example, in case you don't know the order of the target words in advance, I would use a dictionary to store the indices of the found words.对于您的第一个示例,如果您事先不知道目标单词的顺序,我将使用字典来存储找到的单词的索引。 Then you can sort those to put the found words in the second line in the same order as they appeared in the text:然后你可以对它们进行排序,将找到的单词按照它们在文本中出现的顺序放在第二行:

targets = ['this', 'This']
source = 'This and this word should go in the next line.'

target_ixs = {source.find(target): target for target in targets}
line2 = ' '.join([target_ixs[i] for i in sorted(target_ixs)])

line1 = source
for target in targets:
    line1 = line1.replace(target, '')
line1 = line1.replace('  ', ' ').lstrip()

result = line1 + '\n' + line2
print(result)
and word should go in the next line.
This this

Your second example is easier, because you already know which parts of the strings to put in the second line, so you just need to split each string into a list of words and select from those:您的第二个示例更简单,因为您已经知道将字符串的哪些部分放在第二行,因此您只需要将每个字符串拆分为一个单词列表并从中选择:

source = ['This and this', 'word should go', 'in the next']

source_lists = [s.split() for s in source]
line1 = ' '.join([source_list[0] for source_list in source_lists])
line2 = ' '.join([' '.join(source_list[1:]) for source_list in source_lists])

result = line1 + '\n' + line2
print(result)
This word in
and this should go the next

You can probably do quite a bit without much complication using the regular expression library and some python language features.使用正则表达式库和一些 Python 语言功能,您可能可以做很多事情而不会太复杂。 That being said, it depends on how complex the rules are for determining what words go where.话虽如此,这取决于确定单词去向的规则的复杂程度。 Typically, you want to start with a string and "tokenize" it into the constituent words.通常,您希望从一个字符串开始并将其“标记化”为组成词。 See the code example below:请参阅下面的代码示例:

import re
sentence = "This and this word should go in the next line"

all_words = re.split(r'\W+', sentence)
matched_words = " ".join(re.findall(r"this", sentence, re.IGNORECASE))
unmatched_words = " ".join([word for word in all_words if word not in matched_words])

print(f"{unmatched_words}\n{matched_words}")
> and word should go in the next line
  This this
Final Thoughts:最后的想法:

I am by no means a regex ninja so, there may be even more clever things that can be done with just regex patterns and functions.我绝不是一个正则表达式忍者,所以,可能有更聪明的事情可以用正则表达式模式和函数来完成。 Hopefully, this gives you some food for thought at least.希望这至少能让您深思熟虑

Got it:知道了:

data = ['This and this', 'word should go', 'in the next']

first_line = []
second_line = []

for item in data:
    item = item.split(' ')
    
    first_word = item[0]
    
    item.remove(first_word)
    
    others = " ".join(item)
    
    first_line.append(first_word)
    second_line.append(others)
    
print(" ".join(first_line) + "\n" + " ".join(second_line))

My Solution:我的解决方案:

input_data = ['This and this', 'word should go ok', 'this next']

I've slightly altered your test string to better test the code.我稍微修改了您的测试字符串以更好地测试代码。

# Example 1
# Print all words in input_data, moving any word matching the
# string "this" (match is case insensitive) to the next line.

print('Example 1')
lines = ([], [])

for words in input_data:
    for word in words.split():
      lines[word.lower() == 'this'].append(word)

result = ' '.join(lines[0]) + '\n' + ' '.join(lines[1])
print(result)

The code in example 1 sorts each word into the 2-element tuple, lines .示例 1 中的代码将每个单词排序到 2 元素元组lines 中 The key part is the boolean expression that preforms the string comparison.关键部分是执行字符串比较的布尔表达式。

# Example 2
# Print all words in input_data, moving the second and third
# word in any string to the next line.

from itertools import count
print('\nExample 2')
lines = ([], [])

for words in input_data:
    for q in zip(count(), words.split()):
      lines[q[0] in (1, 2)].append(q[1])

result = ' '.join(lines[0]) + '\n' + ' '.join(lines[1])
print(result)

The next solution is basically the same as the first.下一个解决方案与第一个基本相同。 I zip each word to an integer so you know the word's position when you get to the boolean expression which, again, sorts the words into their appropriate list in lines .我将每个单词压缩为一个整数,这样当您到达布尔表达式时,您就知道单词的位置,该表达式再次将单词按排序到适当的列表中。
As you can see, this solution is fairly flexible and can be adjusted to fit a number of scenarios.如您所见,此解决方案相当灵活,可以进行调整以适应多种场景。
Good luck, and I hope this helped!祝你好运,我希望这有帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM