简体   繁体   English

将textwrap与在文本中更改一个单词颜色相结合

[英]Combine textwrap with changing one word colour in text

I'm writing a text game in Python. 我正在用Python编写一个文本游戏。 I've written a function which takes a list of words and changes their colour, while leaving the rest white. 我写了一个函数,它取一个单词列表并改变它们的颜色,而剩下的就是白色。

def highGreen(text, words):
    textWords = text.split(" ")
    highlight = set(textWords).intersection(words)
    for word in textWords:
        if word in highlight:
            print("\033[32m", end="")
            print(word, end=" ")
        else:
            print("\033[0m", end="")
            print(word, end=" ")

My problem is that I can't seem to combine this function with textwrap.wrap or .fill , so when printed onto the console words are broken in random places. 我的问题是我似乎无法将此函数与textwrap.wrap.fill结合使用,因此当打印到控制台上时,单词会在随机位置中被破坏。

I've tried: 我试过了:

text = "This bed is super uncomfortable."
for line in textwrap.wrap(text, 80):
    highGreen(line, ["bed"])

but it still prints everything in one line. 但它仍然在一行中打印所有内容。

The colouring is done in such a weird way because nothing else I tried worked in the Windows 10 console/PyCharm. 着色是以这种奇怪的方式完成的,因为我在Windows 10控制台/ PyCharm中没有尝试过任何其他功能。

Firstly, your text isn't 80 characters long (in fact it's only 32 ) so it would all fit on one line anyway. 首先,你的text长度不是80字符(事实上它只有32 80字符),所以无论如何它都适合一行。 Let's change that to 20 for this example. 对于这个例子,我们将其改为20

Secondly, Your text would be broken up into 20 character chunks, you're just not printing any newlines. 其次,您的文本分为20字符块,您只是不打印任何换行符。 print() usually adds them automatically but since you override that with the end= argument the new line is never printed. print()通常会自动添加它们,但由于您使用end=参数覆盖它,因此永远不会打印新行。

We can fix this by adding a empty print() statement after you call highGreen . 我们可以通过在调用highGreen后添加一个空的print()语句来解决这个highGreen (Remember, print() automatically prints a newline if you don't specify the end= arg) (请记住,如果你没有指定end= arg, print()自动打印换行符)

Example: 例:

text = "This bed is super uncomfortable."
for line in textwrap.wrap(text, 20):
    highGreen(line, ["bed"])
    print() # add this to print newline

Output: 输出:

This bed is super 
uncomfortable.

(The bed prints out green, I'm just not sure how to copy that into StackOverflow) bed打印出绿色,我只是不确定如何将其复制到StackOverflow中)

textwrap is probably confused by the control codes (the result is the same even if the text is longer than the wrap value). textwrap可能被控制代码混淆(即使文本长于换行值,结果也是一样的)。 You might want to try ansiwrap . 您可能想尝试ansiwrap

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

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